zoukankan      html  css  js  c++  java
  • [LeetCode]1114. 按序打印(并发)

    题目

    我们提供了一个类:

    public class Foo {
      public void one() { print("one"); }
      public void two() { print("two"); }
      public void three() { print("three"); }
    }
    三个不同的线程将会共用一个 Foo 实例。

    线程 A 将会调用 one() 方法
    线程 B 将会调用 two() 方法
    线程 C 将会调用 three() 方法
    请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/print-in-order
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题解

    使用synchronzed锁+while(条件)的方式,使用线程的等待通知实现。
    second方法等待firstFinished;third方法等待secondFinished。

    代码

    class Foo {
    
        private Object obj = new Object();
        private boolean firstFinished = false;
        private boolean secondFinished = false;
    
        public Foo() {
            
        }
    
        public void first(Runnable printFirst) throws InterruptedException {
            
            // printFirst.run() outputs "first". Do not change or remove this line.
            synchronized (obj){
                printFirst.run();
                firstFinished = true;
                obj.notifyAll();
            }      
        }
    
        public void second(Runnable printSecond) throws InterruptedException {
            
            // printSecond.run() outputs "second". Do not change or remove this line.
            synchronized(obj){
                while(!firstFinished){
                    obj.wait();
                }
    
                printSecond.run();
                secondFinished = true;
                obj.notifyAll();
            }
        }
    
        public void third(Runnable printThird) throws InterruptedException {
            
            // printThird.run() outputs "third". Do not change or remove this line.
            synchronized(obj){
                while(!secondFinished){
                    obj.wait();
                }
    
                printThird.run();
            }       
        }
    }
    
  • 相关阅读:
    animation循环滚动
    <canvas>简单学习
    月末总结
    回顾-总结(2)
    初识正则
    学习中小项目遇到事
    在炎热的夏天学习以提高效率
    前端存储之cookie、localStorage
    总结(1)
    jQuery
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/12604397.html
Copyright © 2011-2022 走看看