多线程练习
小于 1 分钟
多线程练习
leetcode 1114. 按序打印
题目:https://leetcode.cn/problems/print-in-order/description/
方法一:使用 while 循环
class Foo {
private AtomicInteger firstJobDone = new AtomicInteger(0);
private AtomicInteger secondJobDone = new AtomicInteger(0);
public Foo() {}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first".
printFirst.run();
// mark the first job as done, by increasing its count.
firstJobDone.incrementAndGet();
}
public void second(Runnable printSecond) throws InterruptedException {
while (firstJobDone.get() != 1) {
// waiting for the first job to be done.
}
// printSecond.run() outputs "second".
printSecond.run();
// mark the second as done, by increasing its count.
secondJobDone.incrementAndGet();
}
public void third(Runnable printThird) throws InterruptedException {
while (secondJobDone.get() != 1) {
// waiting for the second job to be done.
}
// printThird.run() outputs "third".
printThird.run();
}
}
方法二:使用锁 + wait
class Foo {
private volatile int flag = 1;
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
synchronized (this){
while (flag != 1) this.wait();
printFirst.run();
flag = 2;
this.notifyAll();
}
}
public void second(Runnable printSecond) throws InterruptedException {
// printSecond.run() outputs "second". Do not change or remove this line.
synchronized (this){
while (flag != 2) this.wait();
flag = 3;
printSecond.run();
this.notifyAll();
}
}
public void third(Runnable printThird) throws InterruptedException {
// printThird.run() outputs "third". Do not change or remove this line.
synchronized (this){
while (flag != 3) this.wait();
printThird.run();
}
}
}
方法三:使用信号量
import java.util.concurrent.Semaphore;
class Foo {
public Semaphore seam_first_two = new Semaphore(0);
public Semaphore seam_two_second = new Semaphore(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
seam_first_two.release();
}
public void second(Runnable printSecond) throws InterruptedException {
seam_first_two.acquire();
printSecond.run();
seam_two_second.release();
}
public void third(Runnable printThird) throws InterruptedException {
seam_two_second.acquire();
printThird.run();
}
}
Powered by Waline v2.15.5