java 線程之間的協作 wait()與notifyAll()

來源:互聯網
上載者:User

標籤: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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.