mediator.java~11~

来自「《深入浅出设计模式》的完整源代码」· JAVA~11~ 代码 · 共 36 行

JAVA~11~
36
字号
package threadmediator;

public class Mediator {
  private int number;//存储槽
  private boolean slotFull = false;
  public int count;//计数器
  void Mediator()
  {
    count=1;
  }
    //同步化,避免两个线程同时执行
  public synchronized void storeMessage (int num) {
    while (slotFull == true)//存储槽没有空间了
      try {
        wait ();
      }
      catch (InterruptedException e) {}
    slotFull = true;
    number = num;
    count++;
    if(count%5==0)System.out.println("");
    notifyAll ();
  }

  public synchronized int retrieveMessage () {
    while (slotFull == false) //存储槽空信息
      try {
        wait ();
      }
      catch (InterruptedException e) {}
    slotFull = false;
    notifyAll ();
    return number;
  }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?