Java多线程同步中的两个特殊类

豆豆网   技术应用频道   2006年11月25日    社区交流

本文详细介绍Java多线程同步中的两个特殊类

public class ATM
{
 Account acc;
 //作为演示,省略了密码验证
 public boolean login(String name)
 {
  if (acc != null) throw new IllegalArgumentException("Already logged in!");
  acc = new Account(name);
  return true;
 }
 public void deposit(float amt)
 {
  acc.deposit(amt);
 }
 public void withdraw(float amt) throws InsufficientBalanceException
 {
  acc.withdraw(amt);
 }
 public float getBalance()
 {
  return acc.getBalance();
 }
 public void logout ()
 {
  acc = null;
 }
}

  下面是ATMTester,在ATMTester中首先生成了10个ATM实例,然后启动10个线程,同时登录John的账户,先查询余额,然后,再提取余额的80%,然后再存入等额的款(以维持最终的余额的不变)。按照我们的预想,应该不会发生金额不足的问题。首先看代码:

public class ATMTester
{
 private static final int NUM_OF_ATM = 10;
 public static void main(String[] args)
 {
  ATMTester tester = new ATMTester();
  final Thread thread[] = new Thread[NUM_OF_ATM];
  final ATM atm[] = new ATM[NUM_OF_ATM];
  for (int i=0; i<NUM_OF_ATM; i++)
  {
   atm[i] = new ATM();
   thread[i] = new Thread(tester.new Runner(atm[i]));
   thread[i].start();
  }
 }
 class Runner implements Runnable
 {
  ATM atm;
  Runner(ATM atm)
  {
   this.atm = atm;
  }
  public void run()
  {
   atm.login("John");
   //查询余额
   float bal = atm.getBalance();
   try
   {
    Thread.sleep(1);
    //模拟人从查询到取款之间的间隔
   }
   catch (InterruptedException e)
   { // ignore it }
    try
    {
      System.out.println("Your balance is:" + bal);
     System.out.println("withdraw:" + bal * 0.8f);
     atm.withdraw(bal * 0.8f);
     System.out.println("deposit:" + bal * 0.8f);
     atm.deposit(bal * 0.8f);
    }
    catch (InsufficientBalanceException e1)
    {
     System.out.println("余额不足!");
    }
    finally
    { atm.logout(); }
   }
  }
}

  运行ATMTester,结果如下(每次运行结果都有所差异):

责编:豆豆技术应用

正在加载评论...