-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLALA.java
97 lines (91 loc) · 1.65 KB
/
LALA.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.jucday01;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestABC {
public static void main(String[] args) {
PrintABC pabc=new PrintABC();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++) {
pabc.LoopA();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++) {
pabc.LoopB();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++) {
pabc.LoopC();
}
}
}).start();
}
}
class PrintABC {
private int i=1;
Lock lock=new ReentrantLock();
private Condition con1=lock.newCondition();
private Condition con2=lock.newCondition();
private Condition con3=lock.newCondition();
public void LoopA() {
try {
Thread.currentThread().sleep(200);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lock.lock();
try {
if(i!=1) {
con1.await();
}
System.out.println("--A--");
con2.signal();
i=2;
}catch(Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void LoopB() {
lock.lock();
try {
if(i!=2) {
con2.await();
}
System.out.println("--B--");
con3.signal();
i=3;
}catch(Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void LoopC() {
lock.lock();
try {
if(i!=3) {
con3.await();
}
System.out.println("--C--");
con1.signal();
i=1;
}catch(Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}