Thingking in Java学习笔记 wait() notifyAll()

本文通过一个汽车打蜡(waxed)和抛光(buffed)的实例,展示了如何使用Java实现线程间的同步与等待。具体实现了两个线程分别进行打蜡和抛光操作,并确保了操作的正确顺序。

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

共享资源是汽车Car,需要不断的打蜡waxed()和抛光buffed(),waxed()要等待buffed()完成,buffed()又要等待waxed()完成 


<pre name="code" class="java">package com.test.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class WaxOMatic {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		Car car=new Car();
		ExecutorService exec=Executors.newCachedThreadPool();
		exec.execute(new WaxOn(car));
		exec.execute(new WaxOff(car));
		
		TimeUnit.SECONDS.sleep(1);
		System.out.println("trying to terminate all threads!!!!!");
		exec.shutdownNow();
	}

}
class Car{
	private boolean waxOn=false;
	public synchronized void waxed(){	//打蜡
		System.out.println("waxOn!");
		waxOn=true;
		notifyAll();
	}
	public synchronized void buffed(){	//抛光
		System.out.println("waxOff!");
		waxOn=false;
		notifyAll();
	}
	public synchronized void waitingForWaxing() throws InterruptedException{
		while(false==waxOn){
			System.out.println("waiting for Waxing!");
			wait();
		}
	}
	public synchronized void waitingForBufferring() throws InterruptedException{
		while(true==waxOn){
			System.out.println("waiting for Bufferring!");
			wait();
		}
	}
}
class WaxOn implements Runnable{
	private Car car;
	public WaxOn(Car c){
		car=c;
	}
	@Override
	public void run(){
		try{
			while(!Thread.interrupted()){
				car.waxed();
				TimeUnit.MILLISECONDS.sleep(200);
				car.waitingForBufferring();
			}
		}catch(InterruptedException e){
			System.out.println("waxed interrupt exception");
		}
		System.out.println("waxed car end-------");
	}
}
class WaxOff implements Runnable{
	private Car car;
	public WaxOff(Car c){
		car=c;
	}
	@Override
	public void run(){
		try{
			while(!Thread.interrupted()){
				car.waitingForWaxing();
				car.buffed();
				TimeUnit.MILLISECONDS.sleep(200);
			}
		}catch(InterruptedException e){
			System.out.println("buffed interrupt exception");
		}
		System.out.println("buffed car end-------");
	}
}




输出:

waxOn!
waxOff!
waxOn!
waxOff!
waxOn!
waxOff!
waxOn!
waxOff!
waiting for Waxing!
waxOn!
waxOff!
trying to terminate all threads!!!!!
buffered car end-------
waxed car end-------
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:838]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值