1. 程式人生 > >JAVA 同步函式

JAVA 同步函式

//僅作為學習筆記

/*
	多執行緒 同步函式 練習

1,明確哪些程式碼是多執行緒執行程式碼
2,明確共享資料
3,明確多執行緒執行程式碼中哪些語句是操作共享資料的


*/

class Bank
{
	private int sum =0;
	//Object obj = new Object();
	public synchronized void add(int a)//同步函式
	{
//		synchronized(obj){//同步程式碼塊
				sum+=a;
				try{Thread.sleep(40);}catch(Exception e){}
				System.out.println("sum = "+ sum);
//		}
	}
	
}

class Client implements Runnable
{
 	private Bank b = new Bank();

	public void run()
	{
		for(int i=0;i<3;i++)
		{
			b.add(100);	
		}
	}
}

class Test
{

	public static void main(String []args)	
	{
			Client c = new Client();
			Thread t1 = new Thread(c);
			Thread t2 = new Thread(c);

			t1.start();
			t2.start();
	}
}