import java.util.concurrent.*;
class AccountSync 
{	
	//AccountÀà¶ÔÏó ±»¶à¸öAddTeskÈÎÎñ¹²Ïí£¬staticÐÞÊÎÊ¼ÖÕÖ»ÓÐÒ»¸öAccountÀà¶ÔÏó
	private static Account account = new Account();
	public static void main(String[] args) 
	{
		ExecutorService executor =  Executors.newCachedThreadPool();
		for (int i=0; i<100; i++)
		{
			executor.execute(new AddTesk());
		}
		//Ò»¶¨Òª¹Ø±Õexecutor£¬²»ÔÙ½ÓÊÜÐÂÈÎÎñ£¬·ñÔò³ö´í
		executor.shutdown();
		while (!executor.isTerminated()){
			int i = 0;
			//System.out.println(++i);
			}
		//ËùÓÐ¸öÏß³ÌÖÕÖ¹executor.isTerninated()¶¼·µ»Øtrue
			
		System.out.println(account.getBalance());
		
		//AccountWithoutSync.Account.print();
	}
	//ÄÚ²¿Àà¿ÉÒÔÓÃprivate ºÍstaticÐÞÊÎ£¬ÒòÎªÄÚ²¿ÀàÊÇÍâ²¿ÀàµÄ³ÉÔ±
	//¾²Ì¬ÄÚ²¿ÀàËùÓÐ³ÉÔ±±äÁ¿×Ô¶¯¾²Ì¬£¿·ñ
	private static class AddTesk implements Runnable
	{
		public void run() {
			account.deposit(1);
		}
	}
	private static class Account
	{   
		/*
		//¾²Ì¬ÄÚ²¿Àà³ÉÔ±±äÁ¿»á×Ô¶¯³õÊ¼»¯Âð?¾­ÑéÖ¤¿ÉÒÔ
		private static int balance;
		public  static void print() {
			System.out.println(balance);
		}
		*/
		
		//private static int balance = 0;
		private static int balance = 0;
		public int getBalance() {
			return balance;
		}
		/*µ÷ÓÃÒ»¸ö¶ÔÏóµÄÍ¬²½·Ç¾²·½·¨£¬synchronized»á¶Ô¸Ã¶ÔÏó¼ÓËø,
		      ´ËÊ±ÁíÒ»¸öµ÷ÓÃÁË¸Ã¶ÔÏóµÄÍ¬²½·Ç¾²·½·¨µÄÏß³Ì½«±»×èÈû
		  µ÷ÓÃÒ»¸öµÄÍ¬²½¾²Ì¬·½·¨£¨ÀàÃû.¾²Ì¬·½·¨Ãû£©£¬
			  synchronized»á¶Ô¸ÃÀà¼ÓËø£¬
			  ´ËÊ±ÁíÒ»¸öµ÷ÓÃÁË¸ÃÀàµÄÍ¬²½¾²Ì¬·½·¨µÄÏß³Ì½«±»×èÈû
			  
		*/

		//public static synchronized void deposit(int amount) {
		public synchronized void deposit(int amount) {
			int newBalance = balance + amount;
			try
			{
				Thread.sleep(10);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			balance = newBalance;
		}

	}
}
