Skip to content

Commit d2a2472

Browse files
committed
printing alternatively
1 parent 8f2e56a commit d2a2472

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

concurrency/fooBarAlternate.java

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.util.concurrent.*;
2+
class FooBar {
3+
private int n;
4+
Semaphore s, a;
5+
public FooBar(int n) {
6+
this.n = n;
7+
s = new Semaphore(1);
8+
a = new Semaphore(0);
9+
}
10+
11+
public void foo(Runnable printFoo) throws InterruptedException {
12+
13+
for (int i = 0; i < n; i++) {
14+
15+
// printFoo.run() outputs "foo". Do not change or remove this line.
16+
s.acquire();
17+
printFoo.run();
18+
a.release();
19+
}
20+
}
21+
22+
public void bar(Runnable printBar) throws InterruptedException {
23+
24+
for (int i = 0; i < n; i++) {
25+
a.acquire();
26+
// printBar.run() outputs "bar". Do not change or remove this line.
27+
printBar.run();
28+
s.release();
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)