题目
https://leetcode-cn.com/problems/print-foobar-alternately/
Semaphore
class FooBar {
private int n;
Semaphore s1=new Semaphore(0);
Semaphore s2=new Semaphore(1);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
s2.acquire();
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
s1.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
s1.acquire();
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
s2.release();
}
}
}
无锁
这玩意提交超时了
class FooBar {
private int n;
volatile boolean ff=true;
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; ) {
if(ff){
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
i++;
ff=false;
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n;) {
if(!ff){
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
i++;
ff=true;
}
}
}
}
CyclicBarrier
它让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续运行。
每个线程调用await方法告诉CyclicBarrier我已经到达了屏障,然后当前线程被阻塞。
class FooBar {
private int n;
public FooBar(int n) {
this.n = n;
}
CyclicBarrier cb = new CyclicBarrier(2);
volatile boolean fin = true;
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(!fin){};
printFoo.run();
fin = false;
try {
cb.await();//第一个线程通过栅栏
} catch (BrokenBarrierException e) {
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
try {
cb.await();//第二个线程通过栅栏
} catch (BrokenBarrierException e) {
}
//已有两个线程通过栅栏,可以允许下述代码了。并且栅栏count重置为2。
printBar.run();
fin = true;
}
}
}