java 线程之间的协作 wait()与notifyAll()

本文展示了一个使用Java实现的简单多线程示例——蜡电气自动方式。该示例中,两个线程分别模拟上蜡和抛光的过程,通过同步方法和条件变量确保正确的执行顺序。最终,通过ExecutorService来管理线程并使用shutdownNow方法优雅地结束所有任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

              

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 buff
		notifyAll();
	}

	// 抛光
	public synchronized void buffed() {
		waxOn = false;// ready to another coat of wax
		notifyAll();
	}

	// 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;
	}

	@Override
	public 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;
	}

	@Override
	public 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
*/




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值