leetcode-1114. 按序打印

题目链接:https://leetcode-cn.com/problems/print-in-order/

题目描述:

我们提供了一个类:

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)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法一(信号量):

class Foo {

    //这里将信号量都设为0是为了保证获取不到许可,只有释放+1之后才会继续,保证了入口方法是哪个
    private Semaphore sem = new Semaphore(0);
    //为什么要设置两个信号量?
    //因为如果是一个信号量的话,其它两个线程都盯着它拿许可的,一旦有了许可就不能保证其它两个线程是谁拿到许可执行了,所以需要另一个他们都获取不到的信号量许可来保证下一个入口方法是哪个
    private Semaphore sem_second = new Semaphore(0);

    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        sem.release();  //将该信号量中的许可释放+1
    }

    public void second(Runnable printSecond) throws InterruptedException {
        //从该信号量中获取一个许可,如果没有可获取的许可就进入阻塞状态,有的话将该信号量中的许可-1
        sem.acquire(); 
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        sem_second.release();  //释放+1
    }

    public void third(Runnable printThird) throws InterruptedException {
        sem_second.acquire();   //获取-1
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}

方法二(计数器):

class Foo {

    //思路和上边的一致,都是保证每一次的方法入口是自己理想中那个
    private CountDownLatch countDownLatch1 = new CountDownLatch(1);
    private CountDownLatch countDownLatch2 = new CountDownLatch(1);

    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        countDownLatch1.countDown(); //将该计数器count -1
    }

    public void second(Runnable printSecond) throws InterruptedException {
        countDownLatch1.await(); //等待该计数器count为0之后才会继续执行,否则该线程会被挂起等待
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        countDownLatch2.countDown(); //将该计数器count -1
    }

    public void third(Runnable printThird) throws InterruptedException {
        countDownLatch2.await(); //该线程挂起等待count为0之后继续执行
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值