Java牛角尖【009】: 多線程中synchronized的鎖定方式

來源:互聯網
上載者:User

  同一個對象中的一個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嗎?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.