⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 clerk.java

📁 JAVA 2入门经典 练习答案
💻 JAVA
字号:
import java.util.List;
import java.util.Collections;
import java.util.LinkedList;

public class Clerk implements Runnable {
  Bank theBank;
  // The in-tray holding transactions:
  private List inTray = Collections.synchronizedList(new LinkedList());
  private String name;

  private int maxTransactions = 8;      // Maximum transactions in the in-tray.

  // Constructor:
  public Clerk(Bank theBank, String name) {
    this.theBank = theBank;         	   // Who the clerk works for.
    this.name = name;
    //inTray     = null;                // Commented out: don't need this now.
  }

  // getName method:
  public String getName() {
    return this.name;
  }

  // Receive a transaction:
  synchronized public void doTransaction(Transaction transaction) {
    while(inTray.size() >= maxTransactions)
    try {
      wait();
    } catch(InterruptedException e) {
      System.out.println(e);
    }
    inTray.add(transaction);
    notifyAll();
  }

  // The working clerk:
  synchronized public void run() {
    while(true) {
      while(inTray.size() == 0)     // No transaction waiting?
        try {
          System.out.println(name + " is idle.");
          wait();                   // Then take a break until there is.
        } catch(InterruptedException e) {
          System.out.println(e);
        }
      System.out.println(name + " is working!");
      theBank.doTransaction((Transaction)inTray.remove(0));
      notifyAll();                  // Notify other threads locked on this clerk.
    }
  }

  // Busy check:
  synchronized public void isBusy() {
    while(inTray.size() != 0)         // 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -