forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintFooBar.java
More file actions
98 lines (78 loc) · 2.3 KB
/
PrintFooBar.java
File metadata and controls
98 lines (78 loc) · 2.3 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
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* https://leetcode-cn.com/problems/print-foobar-alternately/
*/
public class PrintFooBar {
public static void main(String[] args) {
FooBar fooBar = new FooBar(4);
new Thread(() -> {
try {
fooBar.foo(new PrintFoo());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"FOO").start();
new Thread(() -> {
try {
fooBar.bar(new PrintBar());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"Bar").start();
}
}
class FooBar {
private int n;
// 方式一:lock condition
private ReentrantLock lock;
private Condition conditionFoo;
private Condition conditionBar;
private volatile boolean flag;
// 方式二:semaphore
// private Semaphore semaphoreFoo = new Semaphore(1);
// private Semaphore semaphoreBar = new Semaphore(0);
public FooBar(int n) {
this.n = n;
this.lock = new ReentrantLock();
this.conditionFoo = this.lock.newCondition();
this.conditionBar = this.lock.newCondition();
this.flag = false;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
while (flag)
conditionFoo.await();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
flag = true;
conditionBar.signal();
lock.unlock();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
while (!flag)
conditionBar.await();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag = false;
conditionFoo.signal();
lock.unlock();
}
}
}
class PrintFoo implements Runnable {
@Override
public void run() {
System.out.print("Foo");
}
}
class PrintBar implements Runnable {
@Override
public void run() {
System.out.println("Bar");
}
}