码迷,mamicode.com
首页 > 编程语言 > 详细

Java线程同步

时间:2020-03-14 22:07:05      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:account   线程同步   system   catch   print   span   cat   return   for   

public class Accout {

    private static Account account = new Account();
    
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();

        for (int i = 0; i < 1000; i++) {
            executor.execute(new AddAPennyTask());
        }
        executor.shutdown();
        
        while (!executor.isTerminated()){
            
        }
        System.out.println("账户余额:" + account.getBalance());
    }
    
    private static class Account{
        private int balance = 0;
        
        public int getBalance(){
            return balance;
        }
        
        public void deposit(int amount){
            balance = balance + amount;
            try {
                Thread.sleep(10);
            }catch (Exception e ){
                
            }
        }
    }
    
    private static class AddAPennyTask implements Runnable{

        @Override
        public void run() {
            account.deposit(1);
        }
    }
}

结果不可预测:账户余额:980 ? 970? 990?

Java线程同步

标签:account   线程同步   system   catch   print   span   cat   return   for   

原文地址:https://www.cnblogs.com/taiguyiba/p/12494252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!