為什麼會有線程同步的概念呢?為什麼要同步?什麼是線程同步?先看一段代碼:
package com.maso.test; public class ThreadTest2 implements Runnable{ private TestObj testObj = new TestObj(); public static void main(String[] args) { ThreadTest2 tt = new ThreadTest2(); Thread t1 = new Thread(tt, "thread_1"); Thread t2 = new Thread(tt, "thread_2"); t1.start(); t2.start(); } @Override public void run() { for(int j = 0; j < 10; j++){ int i = fix(1); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " : i = " + i); } } public int fix(int y){ return testObj.fix(y); } public class TestObj{ int x = 10; public int fix(int y){ return x = x - y; } } }
輸出結果後,就會發現變數x被兩個線程同時操作,這樣就很容易導致誤操作。如何才能解決這個問題呢?用線程的同步技術,加上synchronized關鍵字
public synchronized int fix(int y){
return testObj.fix(y);
}
加上同步後,就可以看到有序的從9輸出到-10.
如果加到TestObj類的fix方法上能不能實現同步呢?
public class TestObj{
int x = 10;
public synchronized int fix(int y){
return x = x - y;
}
}
如果將synchronized加到方法上則等價於
synchronized(this){
}