日期:2014-05-20 浏览次数:20628 次
package net.xinxin.test; public class BankAccount { private int number; private int balance; public BankAccount(int number,int balance) { this.number=number; this.balance=balance; } public int getBalance() { return balance; } public void deposit(int amount) { balance = balance + amount; } public void withdraw(int amount) { balance = balance-amount; } public static void main(String[] args)throws Exception { BankAccount a = new BankAccount(1, 1000); Thread t1 = new Thread(new Depositor(a, 100),"depositor"); t1.start(); //t1.join(); System.out.println(a.getBalance()); } static class Depositor implements Runnable { BankAccount account; int amount; public Depositor(BankAccount account,int amount) { this.account=account; this.amount=amount; } public void run(){ for(int i=0;i<10000;i++) { account.deposit(amount); //System.out.println(account.getBalance()); //不加此句运行结果1000 加上之后结果正常 } } } static class Withdrawer implements Runnable { BankAccount account; int amount; public Withdrawer(BankAccount account,int amount) { this.account=account; this.amount=amount; } public void run() { for(int i=0;i<10000;i++) account.withdraw(amount); } } }