synchronized是Java中的關鍵字,是一種同步鎖。它修飾的對象有如下幾種:css
/** * @author shuliangzhao * @Title: SyncThread * @ProjectName design-parent * @Description: TODO * @date 2019/6/17 23:25 */ public class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } @Override public void run() { synchronized (this) { try { for (int i = 0;i<5;i++) { System.out.println(Thread.currentThread().getName() + ":" + (count++)); } Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { SyncThread syncThread = new SyncThread(); Thread thread = new Thread(syncThread,"Thread1"); Thread thread1 = new Thread(syncThread,"Thread2"); thread.start(); thread1.start(); } }
運行結果java
Thread1:0 Thread1:1 Thread1:2 Thread1:3 Thread1:4 Thread2:5 Thread2:6 Thread2:7 Thread2:8 Thread2:9
當兩個併發線程(thread1和thread2)訪問同一個對象(syncThread)中的synchronized代碼塊時,在同一時刻只能有一個線程獲得執行,另外一個線程受阻塞,必須等待當前線程執行完這個代碼塊之後才能執行該代碼塊。Thread1和thread2是互斥的,由於在執行synchronized代碼塊時會鎖定當前的對象,只有執行完該代碼塊才能釋放該對象鎖,下一個線程才能執行並鎖定該對象。數組
把SyncThread的調用稍微改一下:併發
Thread thread = new Thread(new SyncThread(),"Thread1"); Thread thread1 = new Thread(new SyncThread(),"Thread2"); thread.start(); thread1.start();
運行結果ide
Thread2:0 Thread1:0 Thread1:2 Thread1:3 Thread2:1 Thread2:5 Thread1:4 Thread2:6 Thread1:7 Thread2:8
這時至關於建立了兩個SyncThread的對象syncThread1和syncThread2,線程thread1執行的是syncThread1對象中的synchronized代碼(run),而線程thread2執行的是syncThread2對象中的synchronized代碼(run);咱們知道synchronized鎖定的是對象,這時會有兩把鎖分別鎖定syncThread1對象和syncThread2對象,而這兩把鎖是互不干擾的,不造成互斥,因此兩個線程能夠同時執行。
b、當一個線程訪問對象的一個synchronized(this)同步代碼塊時,另外一個線程仍然能夠訪問該對象中的非synchronized(this)同步代碼塊函數
/** * @author shuliangzhao * @Title: SyncThread1 * @ProjectName design-parent * @Description: TODO * @date 2019/6/17 23:53 */ public class CountThread implements Runnable{ private static int count; public CountThread() { count = 0; } public void count() { synchronized(this) { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public void print() { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":count:" + (count)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public void run() { String threadName = Thread.currentThread().getName(); if (threadName.equals("A")) { count(); } else if (threadName.equals("B")) { print(); } } public static void main(String[] args) { CountThread countThread = new CountThread(); Thread thread1 = new Thread(countThread, "A"); Thread thread2 = new Thread(countThread, "B"); thread1.start(); thread2.start(); } }
上面代碼中count是一個synchronized的,print是非synchronized的。從上面的結果中能夠看出一個線程訪問一個對象的synchronized代碼塊時,別的線程能夠訪問該對象的非synchronized代碼塊而不受阻塞。
c、指定要給某個對象加鎖this
/** * @author shuliangzhao * @Title: Account * @ProjectName design-parent * @Description: TODO * @date 2019/6/18 0:04 */ public class Account { String name; float amount; public Account(String name, float amount) { this.name = name; this.amount = amount; } //存錢 public void deposit(float amt) { amount += amt; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } //取錢 public void withdraw(float amt) { amount -= amt; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } public float getBalance() { return amount; } } /** * 帳戶操做類 */ class AccountOperator implements Runnable{ private Account account; public AccountOperator(Account account) { this.account = account; } public void run() { synchronized (account) { account.deposit(500); account.withdraw(500); System.out.println(Thread.currentThread().getName() + ":" + account.getBalance()); } } public static void main(String[] args) { Account account = new Account("zhang san", 10000.0f); AccountOperator accountOperator = new AccountOperator(account); final int THREAD_NUM = 5; Thread threads[] = new Thread[THREAD_NUM]; for (int i = 0; i < THREAD_NUM; i ++) { threads[i] = new Thread(accountOperator, "Thread" + i); threads[i].start(); } } }
運行結果spa
Thread0:10000.0 Thread4:10000.0 Thread3:10000.0 Thread2:10000.0 Thread1:10000.0
在AccountOperator 類中的run方法裏,咱們用synchronized 給account對象加了鎖。這時,當一個線程訪問account對象時,其餘試圖訪問account對象的線程將會阻塞,直到該線程訪問account對象結束。也就是說誰拿到那個鎖誰就能夠運行它所控制的那段代碼。
當有一個明確的對象做爲鎖時,就能夠用相似下面這樣的方式寫程序。線程
public void method3(SomeObject obj) { //obj 鎖定的對象 synchronized(obj) { // todo } }
當沒有明確的對象做爲鎖,只是想讓一段代碼同步時,能夠建立一個特殊的對象來充當鎖code
private byte[] lock = new byte[0]; // 特殊的instance變量 public void method() { synchronized(lock) { // todo 同步代碼塊 } } public void run() { }
說明:零長度的byte數組對象建立起來將比任何對象都經濟――查看編譯後的字節碼:生成零長度的byte[]對象只需3條操做碼,而Object lock = new Object()則須要7行操做碼。
Synchronized修飾一個方法很簡單,就是在方法的前面加synchronized,public synchronized void method(){//todo}; synchronized修飾方法和修飾一個代碼塊相似,只是做用範圍不同,修飾代碼塊是大括號括起來的範圍,而修飾方法範圍是整個函數。
public synchronized void run() { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
Synchronized做用於整個方法的寫法。
寫法一:
public synchronized void method() { // todo }
寫法二:
public void method() { synchronized(this) { // todo } }
在用synchronized修飾方法時要注意如下幾點:
class Parent { public synchronized void method() { } } class Child extends Parent { public synchronized void method() { } }
在子類方法中調用父類的同步方法
class Parent { public synchronized void method() { } } class Child extends Parent { public void method() { super.method(); } }
在定義接口方法時不能使用synchronized關鍵字。
構造方法不能使用synchronized關鍵字,但可使用synchronized代碼塊來進行同步
咱們知道靜態方法是屬於類的而不屬於對象的。一樣的,synchronized修飾的靜態方法鎖定的是這個類的全部對象,把SyncThread改造下:
/** * @author shuliangzhao * @Title: SyncThread * @ProjectName design-parent * @Description: TODO * @date 2019/6/17 23:25 */ public class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } public static void testSync() { try { for (int i = 0;i<5;i++) { System.out.println(Thread.currentThread().getName() + ":" + (count++)); } Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public synchronized void run() { testSync(); } public static void main(String[] args) { SyncThread syncThread = new SyncThread(); Thread thread = new Thread(new SyncThread(),"Thread1"); Thread thread1 = new Thread(new SyncThread(),"Thread2"); thread.start(); thread1.start(); } }
運行結果
Thread1:0 Thread1:1 Thread1:2 Thread1:3 Thread1:4 Thread2:0 Thread2:5 Thread2:6 Thread2:7 Thread2:8
syncThread1和syncThread2是SyncThread的兩個對象,但在thread1和thread2併發執行時卻保持了線程同步。這是由於run中調用了靜態方法method,而靜態方法是屬於類的,因此syncThread1和syncThread2至關於用了同一把鎖。
用法
class ClassName { public void method() { synchronized(ClassName.class) { // todo } } }
public class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } public static void testSync() { synchronized (SyncThread.class) { try { for (int i = 0;i<5;i++) { System.out.println(Thread.currentThread().getName() + ":" + (count++)); } Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public synchronized void run() { testSync(); } public static void main(String[] args) { SyncThread syncThread = new SyncThread(); Thread thread = new Thread(new SyncThread(),"Thread1"); Thread thread1 = new Thread(new SyncThread(),"Thread2"); thread.start(); thread1.start(); } }
運行結果
Thread1:0 Thread1:1 Thread1:2 Thread1:3 Thread1:4 Thread2:5 Thread2:6 Thread2:7 Thread2:8 Thread2:9
A. 不管synchronized關鍵字加在方法上仍是對象上,若是它做用的對象是非靜態的,則它取得的鎖是對象;若是synchronized做用的對象是一個靜態方法或一個類,則它取得的鎖是對類,該類全部的對象同一把鎖。B. 每一個對象只有一個鎖(lock)與之相關聯,誰拿到這個鎖誰就能夠運行它所控制的那段代碼。C. 實現同步是要很大的系統開銷做爲代價的,甚至可能形成死鎖,因此儘可能避免無謂的同步控制。