一 修飾方法java
Synchronized修飾一個方法很簡單,就是在方法的前面加synchronized,synchronized修飾方法和修飾一個代碼塊相似,只是做用範圍不同,修飾代碼塊是大括號括起來的範圍,而修飾方法範圍是整個函數。
併發
例如:app
方法一ide
public synchronized void method() { // todo }
方法二函數
public void method() { synchronized(this) { // todo } }
寫法一修飾的是一個方法,寫法二修飾的是一個代碼塊,但寫法一與寫法二是等價的,都是鎖定了整個方法時的內容。this
synchronized關鍵字不能繼承。 spa
雖然可使用synchronized來定義方法,但synchronized並不屬於方法定義的一部分,所以,synchronized關鍵字不能被繼承。若是在父類中的某個方法使用了synchronized關鍵字,而在子類中覆蓋了這個方法,在子類中的這個方法默認狀況下並非同步的,而必須顯式地在子類的這個方法中加上synchronized關鍵字才能夠。固然,還能夠在子類方法中調用父類中相應的方法,這樣雖然子類中的方法不是同步的,但子類調用了父類的同步方法,所以,子類的方法也就至關於同步了。這兩種方式的例子代碼以下: 線程
在子類方法中加上synchronized關鍵字orm
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代碼塊來進行同步。
二 修飾一個代碼塊
1)一個線程訪問一個對象中的synchronized(this)同步代碼塊時,其餘試圖訪問該對象的線程將被阻塞
注意下面兩個程序的區別
class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } public void run() { 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 int getCount() { return count; } } public class Demo00 { public static void main(String args[]){ //test01 // SyncThread s1 = new SyncThread(); // SyncThread s2 = new SyncThread(); // Thread t1 = new Thread(s1); // Thread t2 = new Thread(s2); //test02 SyncThread s = new SyncThread(); Thread t1 = new Thread(s); Thread t2 = new Thread(s); t1.start(); t2.start(); } }
test01的運行結果
test02的運行結果
當兩個併發線程(thread1和thread2)訪問同一個對象(syncThread)中的synchronized代碼塊時,在同一時刻只能有一個線程獲得執行,另外一個線程受阻塞,必須等待當前線程執行完這個代碼塊之後才能執行該代碼塊。Thread1和thread2是互斥的,由於在執行synchronized代碼塊時會鎖定當前的對象,只有執行完該代碼塊才能釋放該對象鎖,下一個線程才能執行並鎖定該對象
爲何上面的例子中thread1和thread2同時在執行。這是由於synchronized只鎖定對象,每一個對象只有一個鎖(lock)與之相關聯。
2)當一個線程訪問對象的一個synchronized(this)同步代碼塊時,另外一個線程仍然能夠訪問該對象中的非synchronized(this)同步代碼塊。
例:
class Counter implements Runnable{ private int count; public Counter() { count = 0; } public void countAdd() { 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(); } } } } //非synchronized代碼塊,未對count進行讀寫操做,因此能夠不用synchronized public void printCount() { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + " count:" + count); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public void run() { String threadName = Thread.currentThread().getName(); if (threadName.equals("A")) { countAdd(); } else if (threadName.equals("B")) { printCount(); } } } public class Demo00{ public static void main(String args[]){ Counter counter = new Counter(); Thread thread1 = new Thread(counter, "A"); Thread thread2 = new Thread(counter, "B"); thread1.start(); thread2.start(); } }
能夠看見B線程的調用是非synchronized,並不影響A線程對synchronized部分的調用。從上面的結果中能夠看出一個線程訪問一個對象的synchronized代碼塊時,別的線程能夠訪問該對象的非synchronized代碼塊而不受阻塞。
3)指定要給某個對象加鎖
/** * 銀行帳戶類 */ 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 class Demo00{ //public static final Object signal = new Object(); // 線程間通訊變量 //將account改成Demo00.signal也能實現線程同步 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(); } } }
運行結果:
在AccountOperator 類中的run方法裏,咱們用synchronized 給account對象加了鎖。這時,當一個線程訪問account對象時,其餘試圖訪問account對象的線程將會阻塞,直到該線程訪問account對象結束。也就是說誰拿到那個鎖誰就能夠運行它所控制的那段代碼。
當有一個明確的對象做爲鎖時,就能夠用相似下面這樣的方式寫程序。
public void method3(SomeObject obj) { //obj 鎖定的對象 synchronized(obj) { // todo } }
當沒有明確的對象做爲鎖,只是想讓一段代碼同步時,能夠建立一個特殊的對象來充當鎖:
class Test implements Runnable { private byte[] lock = new byte[0]; // 特殊的instance變量 public void method() { synchronized(lock) { // todo 同步代碼塊 } } public void run() { } }
本例中去掉註釋中的signal能夠看到一樣的運行結果
三 修飾一個靜態的方法
Synchronized也可修飾一個靜態方法,用法以下:
public synchronized static void method() { // todo }
靜態方法是屬於類的而不屬於對象的。一樣的,synchronized修飾的靜態方法鎖定的是這個類的全部對象。
/** * 同步線程 */ class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } public synchronized static void method() { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void run() { method(); } } public class Demo00{ public static void main(String args[]){ SyncThread syncThread1 = new SyncThread(); SyncThread syncThread2 = new SyncThread(); Thread thread1 = new Thread(syncThread1, "SyncThread1"); Thread thread2 = new Thread(syncThread2, "SyncThread2"); thread1.start(); thread2.start(); } }
syncThread1和syncThread2是SyncThread的兩個對象,但在thread1和thread2併發執行時卻保持了線程同步。這是由於run中調用了靜態方法method,而靜態方法是屬於類的,因此syncThread1和syncThread2至關於用了同一把鎖。
四 修飾一個類
class ClassName { public void method() { synchronized(ClassName.class) { // todo } } }
/** * 同步線程 */ class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } public static void method() { synchronized(SyncThread.class) { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public synchronized void run() { method(); } }
本例的的給class加鎖和上例的給靜態方法加鎖是同樣的,全部對象公用一把鎖
總結
A. 不管synchronized關鍵字加在方法上仍是對象上,若是它做用的對象是非靜態的,則它取得的鎖是對象;若是synchronized做用的對象是一個靜態方法或一個類,則它取得的鎖是對類,該類全部的對象同一把鎖。
B. 每一個對象只有一個鎖(lock)與之相關聯,誰拿到這個鎖誰就能夠運行它所控制的那段代碼。
C. 實現同步是要很大的系統開銷做爲代價的,甚至可能形成死鎖,因此儘可能避免無謂的同步控制。