1. 程式人生 > 實用技巧 >Java執行緒同步

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); } } }