grouptest.java

来自「JAVA 2应用开发指南」· Java 代码 · 共 57 行

JAVA
57
字号
public class groupTest{
  public static void main(String[] args){
    synClass obj;
    Thread thread;
    ThreadGroup group=new ThreadGroup("Thread Group");
    for(int i=0;i<=2;i++){
      obj=new synClass("obj"+i);
      thread=new Thread(group,obj);
      thread.start();
    }
    System.out.println("Press \"Enter\" to stop...");
    try{
      System.in.read();
      group.interrupt();
    }
    catch(Exception e){

    }
  }
}
class synClass implements Runnable{
  private static float balance=5000;
  private String name;
  private int count=0;
  public synClass(String name){
    this.name=name;
  }
  public void run(){
    try{
      while(true){
        if(count%3==0)
          deposit(1000);
        else if(count%3==1)
          withdraw(500);
        else
          getBalance();
        count++;
        Thread.sleep((count%3)*100);
      }
    }
    catch(InterruptedException e){

    }
  }
  public synchronized void getBalance(){
    System.out.println("Balance:"+balance);
  }
  public synchronized void deposit(float n){
    System.out.println(name+"deposits"+n);
    balance+=n;
  }
  public synchronized void withdraw(float n){
    System.out.println(name+"withdraw"+n);
    balance-=n;
  }
}

⌨️ 快捷键说明

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