Java 多執行緒間的通訊 等待喚醒

2021-08-07 10:02:18 字數 1709 閱讀 7054

/*
有兩個執行緒 乙個給名字和性別賦值(input) 乙個輸出名字和性別(output)
但會一下輸出很多同樣的名字和性別(cpu沒切走)
用等待喚醒機制 就可以 1 賦值乙個 然後input wait 喚醒output 2 輸出乙個 output wait 再喚醒input
這樣可以賦值乙個 就輸出乙個
等待/喚醒機制。

涉及的方法:

1 wait(); 讓執行緒處於凍結狀態,被wait的執行緒會被儲存到執行緒池(等待集)中

2 notify();喚醒執行緒池中的乙個執行緒(任意)

3 notifyall();喚醒執行緒池中的所有執行緒

這些方法必須定義在同步中

因為這些方法是用於操作執行緒狀態的方法

必須要明確到底操作的是哪個鎖上的執行緒

為什麼操作執行緒的方法wait notify notifyall 定義在object類中

因為這些方法是監視器的方法,監視器就是鎖

鎖可以是任意物件,任意的物件呼叫的方法一定定義在object中

*/class resource

class input implements runnable

public void run()

catch(interruptedexception e)

}if(x==0)

else

r.flag=true;

r.notify();//喚醒輸出執行緒 可以空喚醒

}x=(x+1)%2;

} }} class output implements runnable

public void run()

catch(interruptedexception e)

} system.out.println(r.name+"------"+r.***);

r.flag=false;

r.notify();

}} }}

class resourcedemo2

}

優化**

class resource

catch(interruptedexception e)

} this.name=name;

this.***=***;

flag=true;

notify();

} public synchronized void out()

catch(interruptedexception e)

}system.out.println("name"+name+"*****"+"***"+***);

flag=false;

notify(); }}

class input implements runnable

public void run()

else

x=(x+1)%2;

} }} class output implements runnable

public void run() }

}class resourcedemo3

}

java執行緒間通訊 等待喚醒機制

等待喚醒機制 涉及方法 1 wait 讓執行緒處於凍結狀態,被wait的執行緒會儲存到執行緒池中 2 notify 喚醒執行緒池中任一線程 隨機 3 nitifyall 喚醒執行緒池中所有執行緒 這些方法必須定義在同步中,因為這些方法是用於操作執行緒狀態的方法,必須要明確操作的是哪個鎖上的執行緒 這...

Java 執行緒間通訊 等待喚醒機制

分析 我們期望的結果是,當輸入執行緒一次 input 操作資源 res 後,我們希望輸入執行緒 input 失去執行權,讓輸出執行緒 output 獲取cpu執行權,當輸出執行緒 output 一次列印完成後,我們希望輸出執行緒 output 失去執行權,這時候讓輸入執行緒 input 獲取執行權,...

144 多執行緒 執行緒間通訊 等待喚醒機制

class res class input implements runnable public void run catch exception e if x 0 else x x 1 2 r.flag true r.notify class output implements runnable ...