clerk.java

来自「Java Classic Examples是我买的两本书:《JAVA经典实例》和」· Java 代码 · 共 64 行

JAVA
64
字号
public class Clerk implements Runnable
{
  private Bank theBank;               // The employer - an electronic marvel
  private Transaction inTray;         // The in-tray holding a transaction

  // Constructor
  public Clerk(Bank theBank)
  {
    this.theBank = theBank;           // Who the clerk works for
    inTray = null;                    // No transaction initially
  }

  // Receive a transaction
  synchronized public void doTransaction(Transaction transaction)
  {
    while(inTray != null)
      try
      {
        wait();
      }
      catch(InterruptedException e)
      {
        System.out.println(e);
      }
    inTray = transaction;
    notifyAll();
  }

  // The working clerk...
  synchronized public void run()
  {
    while(true)
    {
      while(inTray == null)           // No transaction waiting?
        try
        {
          wait();                     // Then take a break until there is
        }
        catch(InterruptedException e)
        {
          System.out.println(e);
        }
      theBank.doTransaction(inTray);
      inTray = null;                // In-tray is empty
      notifyAll();                  // Notify other threads locked on this clerk
    }
  }

  // Busy check 
  synchronized public void isBusy()
  {
    while(inTray != null)             // Is this object busy?
      try
      {
        wait();                       // Yes, so wait for notify call
      }
      catch(InterruptedException e)
      {
        System.out.println(e);
      }
    return;                           // It is free now
  }
}

⌨️ 快捷键说明

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