-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFooBar.java
More file actions
105 lines (74 loc) · 2.34 KB
/
FooBar.java
File metadata and controls
105 lines (74 loc) · 2.34 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
package com.leetcode.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class FooBar {
private static Lock lock=new ReentrantLock();
private static Condition foo=lock.newCondition();
private static Condition bar=lock.newCondition();
private volatile static boolean isRunningFoo=true;
private int n;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
bar.signal();
isRunningFoo=false;
while(!isRunningFoo)
foo.await();
lock.unlock();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
while (isRunningFoo)
bar.await();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
foo.signal();
isRunningFoo=true;
lock.unlock();
}
}
public static void main(String[] args) throws Exception{
Integer n = Integer.parseInt(args[0]);
FooBar fooBar = new FooBar(n);
final Runnable fooRun=new Runnable() {
@Override
public void run() {
System.out.print("foo");
}
};
Runnable barRun=new Runnable() {
@Override
public void run() {
System.out.print("bar");
}
};
new Thread(new Runnable() {
@Override
public void run() {
try {
fooBar.foo(fooRun);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
fooBar.bar(barRun);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}