我们提供了一个类: public class Foo { public void first() { print(“first”); }
public void second() { print(“second”); } public void third() {
print(“third”); } } 三个不同的线程 A、B、C 将会共用一个 Foo 实例。一个将会调用 first() 方法 一个将会调用 second() 方法 还有一个将会调用 third() 方法 请设计修改程序,以确保
second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
力扣(LeetCode)
使用原子类实现
class Foo {
private AtomicInteger atomicInteger = new AtomicInteger(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
atomicInteger.incrementAndGet();
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
while (atomicInteger.get() != 1) {
}
printSecond.run();
atomicInteger.incrementAndGet();
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
while (atomicInteger.get() != 2) {
}
printThird.run();
atomicInteger.incrementAndGet();
}
}
使用阻塞队列
class Foo {
private BlockingQueue<Integer> oneBlockingQueue = new LinkedBlockingQueue<Integer>();
private BlockingQueue<Integer> twoBlockingQueue = new LinkedBlockingQueue<Integer>();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
oneBlockingQueue.put(1);
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
oneBlockingQueue.take();
printSecond.run();
twoBlockingQueue.put(1);
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
twoBlockingQueue.take();
printThird.run();
}
}