exercise19_3.java

来自「java程序设计 机械工业出版社 书籍代码」· Java 代码 · 共 40 行

JAVA
40
字号
// Exercise19_3.java: Demonstrate resource conflict
public class Exercise19_3 {
  private Account account = new Account();
  private Thread[] thread = new Thread[100];

  public static void main(String[] args) {
    Exercise19_3 test = new Exercise19_3();
    System.out.println("What is balance ? " +
      test.account.getBalance());
  }

  public Exercise19_3() {
    ThreadGroup g = new ThreadGroup("group");
    boolean done = false;

    // Create and launch 100 threads
    for (int i = 0; i < 100; i++) {
      thread[i] = new Thread(g, new AddAPennyThread(), "t");
      thread[i].start();
    }

    // Check if all the threads are finished
    while(!done)
      if (g.activeCount() == 0)
        done = true;
  }


  // A thread for adding a penny to the piggy account
  class AddAPennyThread extends Thread {
    public void run() {
      addAPenny(account);
    }
  }

  private synchronized void addAPenny(Account account) {
    account.deposit(1);
  }
}

⌨️ 快捷键说明

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