JUC學習之執行緒8鎖

2021-08-19 02:48:29 字數 2766 閱讀 4818

介紹執行緒8鎖圍繞乙個題目展開,題目:列印的是「one」還是「two」?

1.兩個普通同步方法,兩個執行緒,列印?

public class testthread8monitor 

}).start();

new thread(new runnable()

}).start();

}}class number

public synchronized void gettwo()

}

結果:

2.新增thread.sleep()給getone()方法,列印?

public synchronized void getone() catch (interruptedexception e) 

system.out.println("one");

}

結果:延遲3秒後

3.新增普通方法getthree(),三個執行緒,列印?

public class testthread8monitor 

}).start();

new thread(new runnable()

}).start();

new thread(new runnable()

}).start();

}}class number catch (interruptedexception e)

system.out.println("one");

}public synchronized void gettwo()

public void getthree()

}

結果:先列印three,然後延遲3秒,列印one,two

4.兩個普通同步方法,兩個number物件,列印?

public class testthread8monitor 

}).start();

new thread(new runnable()

}).start();

// new thread(new runnable()

// }).start();

}}class number catch (interruptedexception e)

system.out.println("one");

}public synchronized void gettwo()

// public void getthree()

}

結果:

5.將getone()方法設定成static,乙個物件,兩個執行緒,列印?

public static synchronized void getone() catch (interruptedexception e) 

system.out.println("one");

}

結果:

6.修改兩個方法均為static方法,乙個number物件,列印?

public static synchronized void gettwo()
結果:延遲3秒後列印

7.乙個static同步方法,乙個非static同步方法,兩個物件,列印?

public class testthread8monitor 

}).start();

new thread(new runnable()

}).start();

}}class number catch (interruptedexception e)

system.out.println("one");

}public synchronized void gettwo()

}

結果:列印two之後延遲3秒列印one

8.兩個static同步方法,兩個number物件,列印?

public static synchronized void gettwo()
結果:延遲3秒列印one,two

執行緒八鎖的關鍵:

1.在某一時刻,只有乙個執行緒能夠持有鎖,無論有幾個方法。

2.非static方法的鎖預設為this,static的鎖是class例項。

JUC 執行緒八鎖

1,乙個物件裡面如果有多個synchronized方法,某乙個時刻內,只要乙個執行緒去呼叫其中的乙個synchronized方法了,其它的執行緒都只能等待,換句話說,某乙個時刻內,只能有唯一乙個執行緒去訪問這些synchronized方法。2,鎖的是當前物件this,被鎖定後,其它的執行緒都不能進入...

JUC 執行緒八鎖

package org.meng.juc 題目 判斷列印 one or two 1.兩個普通同步方法,兩個執行緒 標準列印,列印?one two 2.新增thread.sleep 3000 給getone 列印?3s 後列印 one two 3.新增普通方法 getthreee 列印?先列印thre...

JUC之讀寫鎖

是什麼?讀寫分離的鎖。locks包下的 lock condition readwritelock 裡面的readwritelock 讀寫鎖 維護了一對讀寫操作。讀的鎖可以共享 又叫共享鎖 寫的鎖獨佔 又叫獨佔鎖 即寫操作只能開始寫 寫結束,中間不能插入任何寫的操作。怎麼用?如果沒有鎖的情況 publ...