/*** WaitTest* <p>* 欢迎跟我一起学习,微信(lvgocc)公众号搜索:星尘的一个朋友** @author lvgorice@gmail.com* @version 1.0* @blog @see http://lvgo.org* @CSDN @see https://blog.csdn.net/sinat_34344123* @date 2020年12月15日*/public class WaitTest {public static void main(String[] args) {// 创建工厂类Factory factory = new Factory();// 生产者Thread producer = new Thread(() -> {try {factory.put();} catch (InterruptedException e) {e.printStackTrace();}}, "生产者1");producer.start();// 生产者Thread producer2 = new Thread(() -> {try {factory.put();} catch (InterruptedException e) {e.printStackTrace();}}, "生产者2");producer2.start();// 消费者Thread consumer = new Thread(() -> {try {factory.take();} catch (InterruptedException e) {e.printStackTrace();}}, "消费者");consumer.start();}}class Factory {private int[] items = new int[1]; // 数据存储容器(为了演示方便,设置容量最多存储 1 个元素)private int size = 0; // 实际存储大小/*** 生产方法*/public synchronized void put() throws InterruptedException {// 循环生产数据do {while (size == items.length) { // 注意不能是 if 判断// 存储的容量已经满了,阻塞等待消费者消费之后唤醒System.out.println(Thread.currentThread().getName() + " 进入阻塞");this.wait();System.out.println(Thread.currentThread().getName() + " 被唤醒");}System.out.println(Thread.currentThread().getName() + " 开始工作");items[0] = 1; // 为了方便演示,设置固定值size++;System.out.println(Thread.currentThread().getName() + " 完成工作");// 当生产队列有数据之后通知唤醒消费者this.notify();} while (true);}/*** 消费方法*/public synchronized void take() throws InterruptedException {// 循环消费数据do {while (size == 0) {// 生产者没有数据,阻塞等待System.out.println(Thread.currentThread().getName() + " 进入阻塞(消费者)");this.wait();System.out.println(Thread.currentThread().getName() + " 被唤醒(消费者)");}System.out.println("消费者工作~");size--;// 唤醒生产者可以添加生产了this.notifyAll();} while (true);}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。