1 基本概念
synchronized英文意思是同步的,該關鍵字代表這個方法加鎖,不管哪一個線程(如線程A),運行到這個方法時,都要檢查有沒有其它線程B(或者C、D等)正在用這個方法。若有則要等正在使用synchronized方法的線程B(或者C、D)運行完這個方法後再運行此線程A。若沒有則直接運行。有兩種用法可以實現:synchronized 方法和synchronized 塊。
2 程式碼範例
代碼摘自張孝祥老師的線程源碼,示範了synchronized塊、synchronized方法和靜態synchronized方法。
public class TraditionalThreadSynchronized {public static void main(String[] args) {new TraditionalThreadSynchronized().init();}private void init() {final Outputer outputer = new Outputer();// 線程1new Thread(new Runnable() {public void run() {while (true) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}outputer.output1("zhangxiaoxiang");}}}).start();// 線程2new Thread(new Runnable() {public void run() {while (true) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}Outputer.output3("lihuoming");}}}).start();}// 若不測試output3靜態方法,該類就無必要加static。不加static也不影響利用Outputer.class這個鎖static class Outputer {// 和output3用的同一把鎖,這個鎖是該類在記憶體中的位元組碼public void output1(String name) {int len = name.length();synchronized (Outputer.class) {for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}}// 普通方法加synchronized,這個鎖是該類的對象:synchronized(this)// output2和output1,output3用的不是同一把鎖,故無法同步// 將output1中改為synchronized(this)即可和output2同步public synchronized void output2(String name) {int len = name.length();for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}// 靜態方法加synchronized,這個鎖是該類在記憶體中的位元組碼:synchronized (Outputer.class)public static synchronized void output3(String name) {int len = name.length();for (int i = 0; i < len; i++) {System.out.print(name.charAt(i));}System.out.println();}}}