[問題] 關於JAVA synchronized的問題?

作者: SST2000 (BMW 428i)   2020-05-11 08:23:56
請問各位,下面這個範例程式為什麼輸出只會有線程0執行??
ackage Thread02;
public class main {
public static void main(String[] args) {
Mythread02 T2=new Mythread02();
Thread t1=new Thread(T2);
Thread t2=new Thread(T2);
Thread t3=new Thread(T2);
t1.start();
t2.start();
t3.start();
}
下面是宣告的class
package Thread02;
public class Mythread02 implements Runnable {
private int number=100;
public void run() {
synchronized (this) {
try {
Thread.sleep(100);
//
作者: charlie0275 (派大猩)   2020-05-11 10:02:00
在 main 主執行緒加上sleep多等幾秒看看
作者: LZN (秋)   2020-05-11 11:34:00
因為synchronized (this)的關係
作者: ssccg (23)   2020-05-11 14:09:00
在synchronized裡面放sleep並不會把lock釋放另外以你的寫法是搶到的Thread就會一次跑完,如果你是要模擬每個數字都重搶一次,Thread中斷應該放在迴圈裡吧while (true) {synchronized (this) {if (...) {...} else { break; }}Thread.sleep(100);}我猜你想做的效果是這樣如果一定要synchonized在外面,要用wait/notify來控制lock

Links booklink

Contact Us: admin [ a t ] ucptt.com