zoukankan      html  css  js  c++  java
  • leetcode1115

    题目类型:并发

    题目:交替打印

    题目描述:两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。

     1 class FooBar {
     2     private int n;
     3     private boolean tag = true;
     4     // tag为true时,输出foo
     5     // tag为false时,输出bar
     6 
     7     public FooBar(int n) {
     8         this.n = n;
     9     }
    10 
    11     public void foo(Runnable printFoo) throws InterruptedException {
    12 
    13         for (int i = 0; i < n; i++) {
    14             synchronized (this) {
    15                 while (!tag) {
    16                     this.wait();
    17                 }
    18                 // printFoo.run() outputs "foo". Do not change or remove this line.
    19                 printFoo.run();
    20                 tag = false;
    21                 this.notifyAll();
    22             }
    23         }
    24     }
    25 
    26     public void bar(Runnable printBar) throws InterruptedException {
    27 
    28         for (int i = 0; i < n; i++) {
    29             synchronized (this) {
    30                 while(tag) {
    31                     this.wait();
    32                 }
    33                 // printBar.run() outputs "bar". Do not change or remove this line.
    34                 printBar.run();
    35                 tag = true;
    36                 this.notifyAll();
    37             }
    38         }
    39     }
    40 }

    思路:定义变量tag(默认为true),用于线程同步。

    foo()方法只有在tag为true时,才能被线程执行,执行后将tag改为false。

    bar()方法只有在tag为false时,才能被线程执行,执行后将tag改为true。

    tag初始状态为true,因此线程会先调用foo()

  • 相关阅读:
    C# 3.0新特性之扩展方法
    ObservableCollection 类
    Path的Data
    INotifyPropertyChanged 接口
    Django的最佳系统结构
    Django 结构及处理流程分析
    django最佳实践:项目布局
    近期的几个ASP.NET开发经验总结和收集(一)
    Javascript对象Clone
    ASP.NET20 自定义配置节学习笔记(一)
  • 原文地址:https://www.cnblogs.com/asenyang/p/14377698.html
Copyright © 2011-2022 走看看