標籤:executors private java 線程 als rri 暫停 package boolean trace
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()與notifyAll()