- Java code
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); } } }
当仅启动线程,若注释内容System.out.println(account.getBalance());不注释掉,输出结果为1001000,注释掉则为1000.
加t1.join()结果也为1001000.这样是单线程啊,为什么会出现这种情况呢?
------解决方案--------------------
应该说是多线程
main()方法是主线程, Thread t1 是子线程。同时运行。
关于t1.join()
1)注释后,主线程先结束。 子线程运行运行的时间长些。
关于 System.out.println(account.getBalance());
a)注释后,运行正常,不解释了。
b)不注释,从1000开始输出到1001000
2)不注释,主线程等待子线程,最后主线程输出1001000
------解决方案--------------------
System.out.println(a.getBalance());
这一句并不是a.balance的最后值,这句在主线程里面,你那存款的线程若先结束,则是正确的值,否则就不是
你可以增加循环次数,这时候每跑一遍,每次打印的结果可能不同
调用join方法是等到那个线程结束