class Res { private String name; private int count = 1; private boolean flag; public synchronized void set(String name) { while (flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.name = name + "--" + count++; System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name); flag = true; this.notifyAll(); } public synchronized void print() { while (flag) { System.out.println(Thread.currentThread().getName() + "......消费者......" + this.name); flag = false; this.notifyAll(); } } } class Producer implements Runnable { private Res r; public Producer(Res r) { this.r = r; } @Override public void run() { while (true) { r.set("商品"); } } } class Consumer implements Runnable { private Res r; public Consumer(Res r) { this.r = r; } @Override public void run() { while (true) { r.print(); } } } public class ProducerConsumerDemo { public static void main(String[] args) { Res r = new Res(); new Thread(new Producer(r)).start(); new Thread(new Producer(r)).start(); new Thread(new Consumer(r)).start(); new Thread(new Consumer(r)).start(); } }
出现多个生产者消费者要用while重新判断一次标记,并使用notifyAll()唤醒所有,notify可能出现只唤醒本方线程的情况,导致所有线程都等待。
原文地址:https://www.cnblogs.com/hongxiao2020/p/12608866.html
时间: 2024-10-07 11:33:51