dumxz
发贴: 4
积分: 0
|
于 2006-02-17 23:19
我根据您说的修改过了,怎么还是出现错误呀。 public class Li904 implements Runnable { public Li904(Account acc) { this.acc = acc; } public void run() { acc.deposit(20.0f); acc.withdraw(10.0f); }
private static int NUM_OF_THREAD = 100; static Thread[] threads = new Thread[NUM_OF_THREAD];
public static void main(String[] args){ final Account acc = new Account("王红", 1000.0f); for (int i = 0; i< NUM_OF_THREAD; i++) { Li904 my = new Li904(acc); threads[i] = new Thread(my); threads[i].start(); } for (int i=0; i<NUM_OF_THREAD; i++){ try { threads[i].join(); //等待所有线程运行结束 } catch (InterruptedException e) { } } System.out.println("完成,王红的帐户余额为:" + acc.getBalance()); } }
class Account { String name; float amount;
public Account(String name, float amount) { this.name = name; this.amount = amount; }
public void deposit(float amt) { float tmp = amount; tmp += amt;
try { Thread.sleep(1);//模拟其它处理所需要的时间,比如刷新数据库等 } catch (InterruptedException e) { }
amount = tmp; }
public void withdraw(float amt) { float tmp = amount; tmp -= amt;
try { Thread.sleep(1);//模拟其它处理所需要的时间,比如刷新数据库等 } catch (InterruptedException e) { }
amount = tmp; }
public float getBalance() { return amount; } }
|