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

📄 groupexam.java

📁 Java程序设计实用教程源代码 本书源代码按章分别放置在不同的文件夹中,所有程序均在JDK1.6环境下编译运行正常,除了第13章需要建立ODBC数据源之外,其他程序只要有Java运行环境即可直接运行
💻 JAVA
字号:
import java.util.*;
public class groupExam{
  public static void main(String[] args){
    synClass obj;
    Thread thread;
    ThreadGroup group=new ThreadGroup("Thread Group");
    for(int i=1;i<=3;i++){
      obj=new synClass("用户 "+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 = 100;
  private String name;
  private int count = 0;
  public synClass(String name) {
    this.name = name;
  }

  public void run() {
    try {
      Random r = new Random();  //随机调用存取款操作
      while (true) {
        int i = r.nextInt();
        if (i % 3 == 0)
          deposit(1000);
        else if (i % 3 == 1)
          withdraw(500);
        else
          getBalance();
        count++;
        Thread.sleep(100);
      }
    }
    catch (InterruptedException e) {
    }
  }

  public synchronized void getBalance() {
    System.out.println("帐户余额:" + balance);
  }

  public synchronized void deposit(float n) {
    System.out.println(name + " 存入 " + n);
    balance += n;
  }

  public synchronized void withdraw(float n) {
    if (balance >= n) {
      System.out.println(name + " 支取 " + n);
      balance -= n;
    }
    else
      System.out.println(name + " 支取 " + n + " 失败,余额不足");
  }
}

⌨️ 快捷键说明

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