Java线程同步
Posted panzer
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java线程同步相关的知识,希望对你有一定的参考价值。
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线程同步的主要内容,如果未能解决你的问题,请参考以下文章