-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoundPrinter.java
More file actions
100 lines (74 loc) · 2.78 KB
/
RoundPrinter.java
File metadata and controls
100 lines (74 loc) · 2.78 KB
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
package com.leetcode.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class RoundPrinter {
private static volatile long number = 0;
private static volatile int flag = 1;
private static ReentrantLock reentrantLock = new ReentrantLock();
private static Condition conditionOne = reentrantLock.newCondition();
private static Condition conditionTwo = reentrantLock.newCondition();
private static Condition conditionThird = reentrantLock.newCondition();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
reentrantLock.lock();
while (flag != 1) {
conditionOne.await();
}
number++;
System.out.println(Thread.currentThread().getName() + ":" + number);
flag = 2;
conditionTwo.signal();
} catch (Exception e) {
} finally {
reentrantLock.unlock();
}
}
}
}, "thread-1").start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
reentrantLock.lock();
while (flag != 2) {
conditionTwo.await();
}
number++;
System.out.println(Thread.currentThread().getName() + ":" + number);
Thread.sleep(500);
flag = 3;
conditionThird.signal();
} catch (Exception e) {
} finally {
reentrantLock.unlock();
}
}
}
}, "thread-2").start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
reentrantLock.lock();
while (flag != 3) {
conditionThird.await();
}
number++;
System.out.println(Thread.currentThread().getName() + ":" + number);
flag = 1;
conditionOne.signal();
} catch (Exception e) {
} finally {
reentrantLock.unlock();
}
}
}
}, "thread-3").start();
}
}