1. 當synchronized修飾一個static方法時,多線程下,獲取的是類鎖(即Class自己,注意:不是實例),做用範圍是整個靜態方法,做用的對象是這個類的全部對象。多線程
2. 當synchronized修飾一個非static方法時,多線程下,獲取的是對象鎖(即類的實例對象),做用範圍是整個方法,做用對象是調用該方法的對象。ide
結論:類鎖和對象鎖不一樣,他們之間不會產生互斥。spa
代碼演示:線程
public class SynchoronizedDemo { //synchronized修飾非靜態方法 public synchronized void function() throws InterruptedException { for (int i = 0; i <3; i++) { Thread.sleep(1000); System.out.println("function running..."); } } //synchronized修飾靜態方法 public static synchronized void staticFunction() throws InterruptedException { for (int i = 0; i < 3; i++) { Thread.sleep(1000); System.out.println("Static function running..."); } } public static void main(String[] args) { final SynchoronizedDemo demo = new SynchoronizedDemo(); Thread t1 = new Thread(new Runnable() { @Override public void run() { try { staticFunction(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { demo.function(); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); } }
運行結果:
code
Static function running...
function running...
function running...
Static function running...
Static function running...
function running...