leetcode-1115 交替打印
两个线程用一个对象实例,这两个线程各自执行一个方法,该实例的两个方法交替执行
1114题种通过while()循环,造成资源的浪费,并且执行缓慢,本题通过可重入锁和condition
本题也可以通过两个信号量Semaphore来实现并发控制
class FooBar {
private int n;
ReentrantLock lock = new ReentrantLock();
Condition fooCondition = lock.newCondition();
Condition barCondition = lock.newCondition();
boolean flag = true;
public FooBar(int n){
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException{
for(int i = 0; i < n; i++){
lock.lock();
if(!flag){
fooCondition.await();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
flag = false;
barCondition.signal();
lock.unlock();
}
}
public void bar(Runnable printBar) throws InterruptedException{
for(int i = 0; i < n; i++){
lock.lock();
if(flag){
barCondition.await();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag = true;
fooCondition.signal();
lock.unlock();
}
}
}
京公网安备 11010502036488号