# 【Leetcode多线程】- Leetcode1114 按序打印

310 篇文章 17 订阅

## 【Leetcode多线程】- Leetcode1114 按序打印

public class Foo {
public void first() { print(“first”); }
public void second() { print(“second”); }
public void third() { print(“third”); }
}

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". Do not change or remove this line.
printFirst.run();
firstJobDone.incrementAndGet();
}

public void second(Runnable printSecond) throws InterruptedException {
// 自旋
while(firstJobDone.get()!=1){

}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
secondJobDone.incrementAndGet();
}

public void third(Runnable printThird) throws InterruptedException {
while(secondJobDone.get()!=1){

}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}


class Foo {
// 用信号量来解题
private Semaphore spa,spb,spc;
public Foo() {
// 如果这个semaphore为0，那么一个线程调用acquire会被阻塞住
spa = new Semaphore(1);
spb = new Semaphore(0);
spc = new Semaphore(0);
}

public void first(Runnable printFirst) throws InterruptedException {
spa.acquire();
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
// 只有first释放semaphore之后，会使得semaphore值为1，另一个线程才可以调用
spb.release();
}

public void second(Runnable printSecond) throws InterruptedException {
// 只有spa会1才能执行acquire，如果为0就会产生阻塞
spb.acquire();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
spc.release();
}

public void third(Runnable printThird) throws InterruptedException {
// 只有spb会1才能通过，如果为0就会阻塞
spc.acquire();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}


countDownLatch

class Foo {

private CountDownLatch cdla;
private CountDownLatch cdlb;

public Foo() {
cdla = new CountDownLatch(1);
cdlb = new CountDownLatch(1);
}

public void first(Runnable printFirst) throws InterruptedException {

// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
// 计算为0
cdla.countDown();
}

public void second(Runnable printSecond) throws InterruptedException {
// 只有cdla为0才能通过，否则会一直阻塞
cdla.await();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
cdlb.countDown();
}

public void third(Runnable printThird) throws InterruptedException {
cdlb.await();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}

• 1
点赞
• 1
收藏
觉得还不错? 一键收藏
• 打赏
• 1
评论

mind_programmonkey

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。