java线程的wait(_Java多线程之Wait()和Notify()

本文展示了使用Java并发库实现线程同步和协作的示例。通过Car类的waxOn和waxOff方法,模拟了汽车上蜡和抛光的过程,利用wait()和notifyAll()方法实现线程间的通信。WaxOn和WaxOff线程交替进行,展示了如何在多线程环境中协调任务执行。
摘要由CSDN通过智能技术生成

packageThread.Wait;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.TimeUnit;classCar {private boolean waxOn = false;//上蜡

public synchronized voidwaxed() {

waxOn= true;

notifyAll();

}//抛光

public synchronized voidbuffed() {

waxOn= false;

notifyAll();

}public synchronized void waitForWaxing() throwsInterruptedException {while (waxOn == false)

wait();

}public synchronized void waitForBuffing() throwsInterruptedException {while (waxOn == true)

wait();

}

}class WaxOn implementsRunnable {privateCar car;publicWaxOn(Car c) {

car=c;

}

@Overridepublic voidrun() {try{while (!Thread.interrupted()) {

System.out.println("Wax On!");

TimeUnit.MILLISECONDS.sleep(200);

car.waxed();//上完蜡 waxOn = true;notifyAll();

car.waitForBuffing();//等待抛光while (waxOn == true) wait();

}

}catch(Exception e) {

System.out.println("Exiting via interrupt");

}

System.out.println("Ending Wax On task");

}

}class WaxOff implementsRunnable {privateCar car;publicWaxOff(Car c) {

car=c;

}

@Overridepublic voidrun() {try{while (!Thread.interrupted()) {

car.waitForWaxing();//等待上蜡 while (waxOn == false) wait();

System.out.println("Wax Off!");

TimeUnit.MILLISECONDS.sleep(200);

car.buffed();//已经抛光 waxOn = false; notifyAll();

}

}catch(Exception e) {

System.out.println("Exiting via interrupt");

}

System.out.println("Ending Wax Off task");

}

}public classWaxOMatic {public static void main(String[] args) throwsException {

Car car= newCar();

ExecutorService exec=Executors.newCachedThreadPool();

exec.execute(newWaxOff(car));

exec.execute(newWaxOn(car));

TimeUnit.SECONDS.sleep(5);

exec.shutdownNow();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值