1. 程式人生 > >synchronized關鍵字

synchronized關鍵字

[] ava over highlight tile string err args static

  關鍵字synchronized的作用是實現線程間的同步。它的工作是對同步的代碼加鎖,使得每一次,只能有一個線程進入同步塊,從而保證線程間的安全性。

  關鍵字synchronized可以有多種用法:

  1. 指定加鎖對象:對給定對象加鎖,進入同步代碼前要獲得當前實例的鎖。
  2. 直接作用於實例方法:相當於對當前實例加鎖,進入同步代碼前要獲得當前實例的鎖。
  3. 直接作用於靜態方法:相當於對當前類加鎖,進入同步代碼前要獲得當前類的鎖。

  下述代碼,將synchronized作用於一個給定對象instance,因此每次當線程進入被synchronized包裹的代碼段,就都會要求請求instance實例的鎖。如果當前有其他線程正持有這把鎖,那麽新到的線程就必須等待。這樣,就保證了每次只能有一個線程執行i++操作。也可以寫成備註的形式,兩者等價的。

public class AccountingVol implements Runnable {

	static AccountingVol instance = new AccountingVol();
	static volatile int i = 0;
	
//	public synchronized static void increase(){
//		i++;
//	}
	

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int j = 0;j<10000000;j++){
//			increase();
			synchronized(instance){
				i++;
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(instance);
		Thread t2 = new Thread(instance);
		t1.start();t2.start();
		t1.join();t2.join();
		System.out.println(i);
	}
}

  

synchronized關鍵字