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

synchronized 關鍵字詳解

synchronized 鎖

1.鎖什麼

鎖物件

可能鎖的物件包括:this ,  臨界資源物件 (多執行緒都能訪問到的物件), class 類物件。

靜態同步方法,鎖的是當前型別的類物件。

synchronized (使用範圍越小越好)

程式碼貼圖描述:

 

程式執行記憶體示意圖:

上程式碼:

/**
 * synchronized關鍵字
 * 鎖物件。synchronized(this)和synchronized方法都是鎖當前物件。
 */
package concurrent.t01;

import java.util.concurrent.TimeUnit;

public class Test_01 {
	private int count = 0;
	private Object o = new Object();
	
	public void testSync1(){
		synchronized(o){
			System.out.println(Thread.currentThread().getName() 
					+ " count = " + count++);
		}
	}
	
	public void testSync2(){
		synchronized(this){
			System.out.println(Thread.currentThread().getName() 
					+ " count = " + count++);
		}
	}
	
	public synchronized void testSync3(){
		System.out.println(Thread.currentThread().getName() 
				+ " count = " + count++);
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		final Test_01 t = new Test_01();
		new Thread(new Runnable() {
			@Override
			public void run() {
				t.testSync3();
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				t.testSync3();
			}
		}).start();
	}
}




/**
 * synchronized關鍵字
 * 同步方法 - static
 * 靜態同步方法,鎖的是當前型別的類物件。在本程式碼中就是Test_02.class
 */
package concurrent.t01;

import java.util.concurrent.TimeUnit;

public class Test_02 {
	private static int staticCount = 0;
	
	public static synchronized void testSync4(){
		System.out.println(Thread.currentThread().getName() 
				+ " staticCount = " + staticCount++);
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void testSync5(){
		synchronized(Test_02.class){
			System.out.println(Thread.currentThread().getName() 
					+ " staticCount = " + staticCount++);
		}
	}
	
}