同一個對象中的一個synchronized方法如果已有一個線程進入,則其它的線程必須等該線程結束後才能進入該方法。那麼,如果一個類中有多個synchronized方法,會有什麼情況呢?
看下面一段代碼:
public class Test {<br />static Test t = new Test();<br />static Test2 t2 = new Test2();</p><p>public static void main(String[] args) {<br />// TODO Auto-generated method stub</p><p>TestThread tt = t.new TestThread();<br />tt.start();<br />try {<br />Thread.sleep(1000);<br />} catch (InterruptedException e) {<br />// TODO Auto-generated catch block<br />e.printStackTrace();<br />}<br />t2.test1();<br />}</p><p>class TestThread extends Thread {<br />@Override<br />public void run() {<br />// TODO Auto-generated method stub<br />t2.test2();<br />}<br />}<br />}</p><p>class Test2 {<br />public synchronized void test1() {<br />System.out.println("test1 called");<br />}</p><p>public synchronized void test2() {<br />System.out.println("test2 called");<br />try {<br />Thread.sleep(3000);<br />} catch (InterruptedException e) {<br />// TODO Auto-generated catch block<br />e.printStackTrace();<br />}<br />System.out.println("test2 exit");<br />}<br />}
運行結果如下:
test2 called<br />test2 exit<br />test1 called
很明顯,當對象t2的synchronized方法test2被線程tt調用時,主線程也無法進入其test1方法,直到線程tt對test2方法的調用結束,主線程才能進入test1方法。
結論,對於synchronized方法,Java採用的是對象鎖定的方式,當任何一個synchronized方法被訪問的時候,該對象中的其它synchronized方法將全部不能被訪問。
下一篇: Java牛角尖【010】: 當對象a.equals(b)時,a.hashCode == b.hashCode嗎?