1114. 按序打印 - 力扣(LeetCode) (leetcode-cn.com)
方法一:同步原语
private volatile int flag = 1;
private final Object object = new Object();
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
synchronized (object) {
while(flag!=1){
object.wait();
}
printFirst.run();
flag = 2;
object.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
synchronized (object) {
while(flag != 2) {
object.wait();
}
printSecond.run();
flag = 3;
object.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
synchronized (object) {
while (flag != 3) {
object.wait();
}
printThird.run();
}
}
方式二:原子操作类
import java.util.concurrent.atomic.AtomicInteger;
class Foo {
private final AtomicInteger flag = new AtomicInteger(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
flag.incrementAndGet();
}
public void second(Runnable printSecond) throws InterruptedException {
while (flag.get() != 1) {
}
printSecond.run();
flag.incrementAndGet();
}
public void third(Runnable printThird) throws InterruptedException {
while (flag.get() != 2) {
}
printThird.run();
}
}
方式三:CountDownLatch
class Foo {
private final CountDownLatch first;
private final CountDownLatch second;
public Foo() {
first = new CountDownLatch(1);
second = new CountDownLatch(1);
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
first.countDown();
}
public void second(Runnable printSecond) throws InterruptedException {
first.await();
printSecond.run();
second.countDown();
}
public void third(Runnable printThird) throws InterruptedException {
second.await();
printThird.run();
}
}
方法四:Semaphore
private Semaphore semaphore = new Semaphore(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
semaphore.release();
}
public void second(Runnable printSecond) throws InterruptedException {
while(semaphore.availablePermits() != 1) {
}
printSecond.run();
semaphore.release();
}
public void third(Runnable printThird) throws InterruptedException {
while(semaphore.availablePermits()!=2) {
}
printThird.run();
}