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
| class FooBar { private int n; private Semaphore fooSem, barSem; public FooBar(int n) { this.n = n; fooSem = new Semaphore(1); barSem = new Semaphore(0); }
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
fooSem.acquire(); printFoo.run(); barSem.release(); } }
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
barSem.acquire(); printBar.run(); fooSem.release(); } } }
|