-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrintFooBar.java
36 lines (30 loc) · 935 Bytes
/
PrintFooBar.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
class FooBar {
private int n;
private Semaphore fooSem, barSem;
public FooBar(int n) {
this.n = n;
fooSem = new Semaphore(1);
barSem = new Semaphore(1);
try {
barSem.acquire();
} catch (InterruptedException e) {
System.out.println(":(");
}
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
fooSem.acquire();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
barSem.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
barSem.acquire();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
fooSem.release();
}
}
}