Java牛角尖【009】: 多线程中synchronized的锁定方式
? 同一個對象中的一個synchronized方法如果已有一個線程進入,則其它的線程必須等該線程結束后才能進入該方法。那么,如果一個類中有多個synchronized方法,會有什么情況呢?
? 看下面一段代碼:
public class Test { static Test t = new Test(); static Test2 t2 = new Test2(); public static void main(String[] args) { // TODO Auto-generated method stub TestThread tt = t.new TestThread(); tt.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t2.test1(); } class TestThread extends Thread { @Override public void run() { // TODO Auto-generated method stub t2.test2(); } } } class Test2 { public synchronized void test1() { System.out.println("test1 called"); } public synchronized void test2() { System.out.println("test2 called"); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("test2 exit"); } }
? 運行結果如下:
test2 called test2 exit test1 called
? 很明顯,當對象t2的synchronized方法test2被線程tt調用時,主線程也無法進入其test1方法,直到線程tt對test2方法的調用結束,主線程才能進入test1方法。
? 結論,對于synchronized方法,Java采用的是對象鎖定的方式,當任何一個synchronized方法被訪問的時候,該對象中的其它synchronized方法將全部不能被訪問。
?
? 下一篇: Java牛角尖【010】: 當對象a.equals(b)時,a.hashCode == b.hashCode嗎?
轉載于:https://www.cnblogs.com/moonsnow/archive/2009/06/11/6226852.html
總結
以上是生活随笔為你收集整理的Java牛角尖【009】: 多线程中synchronized的锁定方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 互动直播娱乐平台宣传文案30句
- 下一篇: 华为新品曝光 华为新品爆料)