java线程同步问题
为什么去了while(!excutor.isTerminated()){}不行?纳闷?
线程同步问题:要求建立100个线程,每个线程往账户添加一元钱,最后得个100元,去了那一句,就TM成1了。。
源码:这是得出100的源码
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class xianChengTongBu {
private static Account account=new Account();
public static void main(String[] args) {
ExecutorService excutor=Executors.newCachedThreadPool();
for(int i=0;i<100;i++){
excutor.execute(new AddTask());
}
excutor.shutdown();
while(!excutor.isTerminated()){}
System.out.print(" "+account.getBalance());
}
private static class Account{
// private static Lock lock=new ReentrantLock();
private int balance=0;
public int getBalance(){
return balance;
}
public synchronized void desposit(int amount){
// lock.lock();
try{
int newBalance=balance+amount;
Thread.sleep(5);
balance=newBalance;
}
catch (InterruptedException e){
}
/* finally{
lock.unlock();
}*/
}
}
private static class AddTask implements Runnable{
public void run(){
account.desposit(1);
}
}
}
------解决方案--------------------
isTerminated()
如果关闭后所有任务都已完成,则返回 true。
=======================================
线程没有执行完成。
------解决方案--------------------
对账户的操作抽成一个方法,然后对方法加锁就可以了