关于Java的wait和notify的直观解答

package com.test;

public class UsingWaitAndNotify {
	public static void main(String[] args) {
		Cup cup = new Cup();
		Thread maker = new Thread(new Maker(cup));
		maker.start();
		Thread washer = new Thread(new Washer(cup));
		washer.start();
	}
}

class Cup {
	private boolean washed = false;
	
	public synchronized void makeTea() throws InterruptedException {
		System.out.println("Maker>>准备泡茶");
		if (!washed) {
			System.out.println("Maker>>很无奈,杯子是脏的,我只有等它被洗干净,我自己懒得动手洗");
			wait();
		}
		System.out.println("Maker>>终于拿到干净的杯子了,开始泡一杯清茶");
	}

	public synchronized void washCup() throws InterruptedException {
		System.out.println("Washer>>正在洗杯子");
		Thread.sleep(3000);
		washed = true;
		notifyAll();
		System.out.println("Washer>>杯子洗干净了,你可以拿去泡茶用了");
	}
}

class Washer implements Runnable {
	private Cup cup;

	public Washer(Cup cup) {
		this.cup = cup;
	}

	public void run() {
		System.out.println(this.getClass().getSimpleName() + ">>我是清洁工,开始洗杯子");
		try {
			cup.washCup();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Maker implements Runnable {
	private Cup cup;

	public Maker(Cup cup) {
		this.cup = cup;
	}

	public void run() {
		System.out.println(this.getClass().getSimpleName() + ">>我是泡茶工,我开始泡茶");
		try {
			cup.makeTea();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

运行结果:
Maker>>我是泡茶工,我开始泡茶
Washer>>我是清洁工,开始洗杯子
Maker>>准备泡茶
Maker>>很无奈,杯子是脏的,我只有等它被洗干净,我自己懒得动手洗
Washer>>正在洗杯子
Washer>>杯子洗干净了,你可以拿去泡茶用了
Maker>>终于拿到干净的杯子了,开始泡一杯清茶

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值