多線程開發離不開鎖機制,現在的Java語言中,提供了2種鎖,一種是語言特性提供的內置鎖,還有一種是 java.util.concurrent.locks 包中的鎖,這篇文章簡單整理一下內置鎖的知識點。
內置鎖在Java語言中的表現:
多線程的鎖,其實本質上就是給一塊內存空間的訪問添加訪問權限,因為Java中是沒有辦法直接對某一塊內存進行操作的,又因為Java是面向對象的語言,一切皆對象,所以具體的表現就是某一個對象承擔鎖的功能,每一個對象都可以是一個鎖。內置鎖,使用方式就是使用 synchronized 關鍵字,synchronized 方法或者 synchronized 代碼塊。
每一種 synchronized 寫法的鎖是哪個對象:
1、指定當前對象加鎖:
private synchronized void function() { //TODO execute something }
2、指定當前類的Class對象加鎖:
private static synchronized void function() { //TODO execute something }
注意此處的 static 關鍵字。
3、指定任意對象加鎖:
private void function() { synchronized (object) { //TODO execute something } }
此時,這段同步代碼塊的鎖加在object對象上面。該對象可以是當前對象(object == this),也可以是當前類的Class對象(object == MyClass.class)。
簡單驗證一下:
現有如下的類:
public class SynchronizedTest { private Object lock = new Object(); public void synchronizedBlockOnObject(long executeTime) { synchronized (lock) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnObject"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnObject"); } } public void synchronizedBlockOnThis(long executeTime) { synchronized (this) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnThis"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnThis"); } } public void synchronizedBlockOnClass(long executeTime) { synchronized (SynchronizedTest.class) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedBlockOnClass"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedBlockOnClass"); } } public synchronized void synchronizedMethodOnThis(long executeTime) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedMethodOnThis"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedMethodOnThis"); } public static synchronized void synchronizedMethodOnClass(long executeTime) { System.out.println(Thread.currentThread().getName() + " -> start synchronizedMethodOnClass"); doSomething(executeTime); System.out.println(Thread.currentThread().getName() + " -> end synchronizedMethodOnClass"); } private static void doSomething(long executeTime) { try { Thread.sleep(executeTime); } catch (InterruptedException e) { e.printStackTrace(); } } }
1、static synchronized 方法 和 synchronized (MyClass.class) {} 同步代碼塊的鎖都加在 MyClass.class 對象上面:
public static void main(String[] args) { SynchronizedTest synchronizedTest = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { SynchronizedTest.synchronizedMethodOnClass(3000); } }, "Thread static synchronized method").start(); new Thread(new Runnable() { @Override public void run() { synchronizedTest.synchronizedBlockOnClass(2000); } }, "Thread synchronized block on Class").start(); }
運行結果如下:
Thread static synchronized method -> start synchronizedMethodOnClass Thread static synchronized method -> end synchronizedMethodOnClass Thread synchronized block on Class -> start synchronizedBlockOnClass Thread synchronized block on Class -> end synchronizedBlockOnClass
說明當線程 Thread static synchronized method 進入方法 synchronizedMethodOnClass 的時候,線程Thread synchronized block on Class 是不能進入synchronizedBlockOnClass 代碼塊的。
2、非 static 的 synchronized 方法和 synchronized (this) {} 同步代碼塊的鎖都加在當前對象上面:
public static void main(String[] args) { SynchronizedTest synchronizedTest = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { synchronizedTest.synchronizedMethodOnThis(3000); } }, "Thread non-static synchronized method").start(); new Thread(new Runnable() { @Override public void run() { synchronizedTest.synchronizedBlockOnThis(2000); } }, "Thread synchronized block on this").start(); }
運行結果如下:
Thread non-static synchronized method -> start synchronizedMethodOnThis Thread non-static synchronized method -> end synchronizedMethodOnThis Thread synchronized block on this -> start synchronizedBlockOnThis Thread synchronized block on this -> end synchronizedBlockOnThis
說明當線程 Thread non-static synchronized method 進入方法 synchronizedMethodOnThis 的時候,線程Thread synchronized block on this 是不能進入synchronizedBlockOnThis 代碼塊的。
3、當鎖加在 MyClass.class 、 this 、 任意對象,這三種情況,起不到任何同步作用:
public static void main(String[] args) { SynchronizedTest synchronizedTest = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { synchronizedTest.synchronizedMethodOnThis(3000); } }, "Thread non-static synchronized method").start(); new Thread(new Runnable() { @Override public void run() { SynchronizedTest.synchronizedMethodOnClass(2000); } }, "Thread static sybchronized method").start(); new Thread(new Runnable() { @Override public void run() { synchronizedTest.synchronizedBlockOnObject(4000); } }, "Thread sybchronized block on other Object").start(); }
運行結果如下:
Thread non-static synchronized method -> start synchronizedMethodOnThis Thread static sybchronized method -> start synchronizedMethodOnClass Thread sybchronized block on other Object -> start synchronizedBlockOnObject Thread static sybchronized method -> end synchronizedMethodOnClass Thread non-static synchronized method -> end synchronizedMethodOnThis Thread sybchronized block on other Object -> end synchronizedBlockOnObject
說明當鎖沒有加在同一個對象上的時候,起不到線程間的同步作用。
Object中對內置鎖進行操作的一些方法:
wait()系列:
wait()系列方法的作用是:使當前已經獲得該對象鎖的線程進入等待狀態,並且釋放該對象的鎖。
notify()系列:
notify()系列方法的作用是:喚醒那些正在等待該對象鎖的線程,使其繼續運行。
基於wait() notify()機制,我們可以實現一個簡易的生產者-消費者模型。
大體思路如下,一個生產者線程負責向一個倉庫中存放(put)物品,一個消費者線程負責從倉庫中取出(get)物品。
代碼如下:
public class Warehouse { private Queue<Integer> queue; private int capacity; public Warehouse(int capacity) { this.capacity = capacity; queue = new LinkedList(); } public synchronized void put(int num) { if (queue.size() >= capacity) { try { System.out.println(Thread.currentThread().getName() + " , put full wait"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } queue.add(num); System.out.println(Thread.currentThread().getName() + " , put : " + num + " , queue -> " + queue); notifyAll(); } public synchronized int get() { if (queue.isEmpty()) { try { System.out.println(Thread.currentThread().getName() + " , get empty wait"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int num = queue.poll(); System.out.println(Thread.currentThread().getName() + " , get : " + num + " , queue -> " + queue); notifyAll(); return num; } }
public static void main(String[] args) { Warehouse warehouse = new Warehouse(4); Random random = new Random(); new Thread(new Runnable() { @Override public void run() { while (true) { warehouse.put(random.nextInt(10)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "生產者-01").start(); new Thread(new Runnable() { @Override public void run() { while (true) { warehouse.get(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }, "消費者-01").start(); }
運行結果如下:
生產者-01 , put : 5 , queue -> [5] 消費者-01 , get : 5 , queue -> [] 生產者-01 , put : 7 , queue -> [7] 消費者-01 , get : 7 , queue -> [] 生產者-01 , put : 9 , queue -> [9] 生產者-01 , put : 7 , queue -> [9, 7] 消費者-01 , get : 9 , queue -> [7] 生產者-01 , put : 0 , queue -> [7, 0] 生產者-01 , put : 5 , queue -> [7, 0, 5] 消費者-01 , get : 7 , queue -> [0, 5] 生產者-01 , put : 9 , queue -> [0, 5, 9] 生產者-01 , put : 6 , queue -> [0, 5, 9, 6] 消費者-01 , get : 0 , queue -> [5, 9, 6] 生產者-01 , put : 4 , queue -> [5, 9, 6, 4] 生產者-01 , put full wait 消費者-01 , get : 5 , queue -> [9, 6, 4] 生產者-01 , put : 6 , queue -> [9, 6, 4, 6] 生產者-01 , put full wait 消費者-01 , get : 9 , queue -> [6, 4, 6] 生產者-01 , put : 2 , queue -> [6, 4, 6, 2] 生產者-01 , put full wait 消費者-01 , get : 6 , queue -> [4, 6, 2] 生產者-01 , put : 9 , queue -> [4, 6, 2, 9] 生產者-01 , put full wait 消費者-01 , get : 4 , queue -> [6, 2, 9] 生產者-01 , put : 7 , queue -> [6, 2, 9, 7] 生產者-01 , put full wait 消費者-01 , get : 6 , queue -> [2, 9, 7] 生產者-01 , put : 2 , queue -> [2, 9, 7, 2]