• leetcode1114


    题目类型:并发

    题目:按序打印

    描述:请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。

     1 class Foo {
     2     private int t = 0;
     3 
     4     public Foo() {
     5 
     6     }
     7 
     8     public synchronized void first(Runnable printFirst) throws InterruptedException {
     9         while (t != 0) {
    10             this.wait();
    11         }
    12         // printFirst.run() outputs "first". Do not change or remove this line.
    13         printFirst.run();
    14         t++;
    15         this.notifyAll();
    16     }
    17 
    18     public synchronized void second(Runnable printSecond) throws InterruptedException {
    19         while (t != 1) {
    20             this.wait();
    21         }
    22         // printSecond.run() outputs "second". Do not change or remove this line.
    23         printSecond.run();
    24         t++;
    25         this.notifyAll();
    26     }
    27 
    28     public synchronized void third(Runnable printThird) throws InterruptedException {
    29         while (t != 2) {
    30             this.wait();
    31         }
    32         // printThird.run() outputs "third". Do not change or remove this line.
    33         printThird.run();
    34         t++;
    35         this.notifyAll();
    36     }
    37 }

    思路:使用线程同步。定义变量t,

    first()需要在t为0时才能被线程执行,执行后将t自增1,修改为1。

    second()需要在t为1时才能被线程执行,执行后将t自增1,修改为2。

    third()需要在t为2时才能被线程执行,执行后将t自增1。

  • 相关阅读:
    C语言写数据库(三)
    C语言写数据库(一)
    KMP 串的模式匹配 (25 分)
    11-散列4 Hashing
    11-散列3 QQ帐户的申请与登陆 (25 分)
    11-散列1 电话聊天狂人 (25 分)
    11-散列2 Hashing (25 分)
    am335x system upgrade uboot nand boot(三)
    am335x system upgrade uboot ethernet(二)
    am335x system upgrade uboot sd boot(一)
  • 原文地址:https://www.cnblogs.com/asenyang/p/14377624.html
Copyright © 2020-2023  润新知