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();
            }       
        }
    }
    
  • 相关阅读:
    [UE4]创建多把枪,使用Class,参数的对象类型
    [UE4]换枪需要做的事,容器:数组、集合、Map
    [UE4]蓝图重构
    [UE4]为什么会有类型检查
    [UE4]ChildActor组件
    [UE4]Character,飞行模式。
    [UE4]Pawn和Controller,第一人称和第三人称切换
    [UE4]组件
    [UE4]Acotr
    [UE4]封装、继承、多态
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/12604397.html
Copyright © 2011-2022 走看看