java 線程之間的協作 wait()與notifyAll(),waitnotifyall
package org.rui.thread.block;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;// wax蠟 電氣自動方式public class WaxOMatic {public static void main(String[] args) throws InterruptedException {Car car = new Car();ExecutorService exec = Executors.newCachedThreadPool();exec.execute(new WaxOff(car));exec.execute(new WaxOn(car));TimeUnit.SECONDS.sleep(5);exec.shutdownNow();// 中斷所有任務// shutdownNow 試圖停止所有正在執行的活動任務,暫停處理正在等待的任務,並返回等待執行的工作清單}}class Car {//表示 拋光 、上蠟的處理狀態private boolean waxOn = false;// 上蠟public synchronized void waxed() {waxOn = true;// ready to buffnotifyAll();}// 拋光public synchronized void buffed() {waxOn = false;// ready to another coat of waxnotifyAll();}// wait 上蠟public synchronized void waitForWaxing() throws InterruptedException {while (waxOn == false) {wait();//掛起這個任務}}// wait 拋光public synchronized void waitForBuffing() throws InterruptedException {while (waxOn == true) {wait();//掛起這個任務}}}class WaxOn implements Runnable {private Car car;public WaxOn(Car c) {car = c;}@Overridepublic void run() {try {while (!Thread.interrupted()) {System.out.println("wax on!");TimeUnit.MILLISECONDS.sleep(200);car.waxed();// 上蠟 car.waitForBuffing();//等 拋光}} catch (InterruptedException e) {System.out.println("通過中斷退出");// e.printStackTrace();}System.out.println("ending Wax on task");}}// /////////////////////class WaxOff implements Runnable {private Car car;public WaxOff(Car c) {car = c;}@Overridepublic void run() {try {while (!Thread.interrupted()) {car.waitForWaxing();//等 吐蠟System.out.println("wax off!");TimeUnit.MILLISECONDS.sleep(200);car.buffed();//拋光}} catch (InterruptedException e) {System.out.println("通過中斷退出");// e.printStackTrace();}System.out.println("ending Wax Off task");}}/*output:(95% match) wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!wax off!wax on!通過中斷退出ending Wax on task通過中斷退出ending Wax Off task*/
Java中有關線程的函數,wait()與notify()有什不同,都是讓本線程停止執行、讓其它線程執行?
你應該不是問wait()和notify()的區別。wait()是使一個線程進如等待狀態,而notify()或者notifyall()是喚醒等待的線程,使之繼續執行。
我想你應該是想問:wait()和sleep(long n)的區別。
主要區別是wait()使線程釋放資源,然後處於等待的狀態,而sleep()只是讓線程睡眠指定的時間n,而不釋放它佔有的資源。
JAVA線程問題 用wait();了 用notifyAll();怎沒喚醒菜鳥解最好有代碼
樓主,你寫錯了哦,你的線程是沒有迴圈的,執行完一次就結束了,當然不會一直執行下去啊,改成下面的:(加一個while迴圈)
public class Work_4_2 {
public static void main(String[] args) {
Ticket myTicket = new Ticket();
new Thread(myTicket).start();
new Thread(myTicket).start();
new Thread(myTicket).start();
new Thread(myTicket).start();
new Thread(myTicket).start();
}
}
class Ticket implements Runnable {
static int a = 100;
public void run() {
synchronized (this) {
while (true) {
if (a < 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(a--);
notifyAll();
}
}
}
}