Java線程中若是給方法加鎖,有一些陷井。下面用些例子進行詳解ide
先構建一個Task類有兩個執行方法測試
class Task { public void excute1(String threadName) { for (int i = 0; i <= 20; i++) { System.out.println(threadName + " ------ " + i); } } public void excute2(String threadName){ for (int i = 0; i <= 20; i++) { System.out.println(threadName + " ------ " + i); } } }
兩個線程來分別調用Task中的excute1,excute2方法this
ThreadA線程
class ThreadA extends Thread { private Task task; public ThreadA(Task task) { this.task = task; } @Override public void run() { task.excute1(this.getName()); } }
ThreadBcode
class ThreadB extends Thread { private Task task; public ThreadB(Task task) { this.task = task; } @Override public void run() { task.excute2(this.getName()); } }
用一個測試類進行測試對象
public class SychronizeTest { public static void main(String[] args) { Task t = new Task(); ThreadA ta = new ThreadA(t); ThreadB tb = new ThreadB(t); ta.start(); tb.start(); } }
這時候測試,代碼執行結果會兩個線程錯亂。。。,若是想有序執行,就須要加入Sychronized 關鍵字到excute1 和 excute2上。get
class Task { public synchronized void excute1(String threadName) { for (int i = 0; i <= 20; i++) { System.out.println(threadName + " ------ " + i); } } public synchronized void excute2(String threadName){ for (int i = 0; i <= 20; i++) { System.out.println(threadName + " ------ " + i); } } }
雖然說兩個線程執行不一樣的方法,可是結果仍是會有序的執行,緣由是當訪問某個對象的Synchronized方法時,表示將對該對象上鎖,此時其它任何線程都沒法訪問該對象下的synchronized方法,直接該對象把鎖釋放掉,其它線程才能夠訪問class