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
98
99
100
101
102
|
package
com.weeya.nine;
import
java.util.concurrent.locks.Condition;
import
java.util.concurrent.locks.Lock;
import
java.util.concurrent.locks.ReentrantLock;
/**
* @author skyarac
* 三个线程 老大唤醒老二,老二唤醒老三,老三唤醒老大
* 2013年12月16日
*/
public
class
ThreeConditionCommunication {
public
static
void
main(String[] args) {
final
Business business =
new
Business();
new
Thread(
new
Runnable() {
//老大线程
@Override
public
void
run() {
for
(
int
i =
1
; i <=
50
; i++) {
business.main(i);
}
}
}).start();
new
Thread(
new
Runnable() {
//老二线程
@Override
public
void
run() {
for
(
int
i =
1
; i <=
50
; i++) {
business.sub2(i);
}
}
}).start();
new
Thread(
new
Runnable() {
//老三线程
@Override
public
void
run() {
for
(
int
i =
1
; i <=
50
; i++) {
business.sub3(i);
}
}
}).start();
}
}
class
Business {
Lock lock =
new
ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private
int
shouldSub =
1
;
/*
* @param i 老大
*/
public void main(int i) {
lock.lock();
while (shouldSub != 1) { // 这里可以使用if循环
try {
condition1.await();// 主线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("老大 sequence of " + j + ",loop of " + i);
}
shouldSub = 2;
condition2.signal();
lock.unlock();
}
/*
* @param i 老二
*/
public void sub2(int i) {
lock.lock();
while (shouldSub != 2) { // 这里可以使用if循环
try {
condition2.await(); // 子线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("老二 sequence of " + j + ",loop of " + i);
}
shouldSub = 3;
condition3.signal();
lock.unlock();
}
/*
* @param i 老三
*/
public
void
sub3(
int
i) {
lock.lock();
while
(shouldSub !=
3
) {
// 这里可以使用if循环
try
{
condition3.await();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
for
(
int
j =
1
; j <=
10
; j++) {
System.out.println(
"老三 sequence of "
+ j +
",loop of "
+ i);
}
shouldSub =
1
;
condition1.signal();
lock.unlock();
}
}
|