https://blog.csdn.net/qq_40550018/article/details/87859399
//商品类 public class Goods { private int id; private String name; public Goods(int id, String name) { this.id = id; this.name = name; } } //消费者类 public class Producer implements Runnable { private Goods goods; @Override public void run() { while (true) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TestPC.queue) { goods=new Goods(1,"商品"); if (TestPC.queue.size()<MAX_POOL) { TestPC.queue.add(goods); System.out.println(Thread.currentThread().getName()+"生产商品"); } else { try { TestPC.queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } //生产者类 public class Consumer implements Runnable { @Override public void run() { while (true){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TestPC.queue){ if(!TestPC.queue.isEmpty()){ TestPC.queue.poll(); System.out.println(Thread.currentThread().getName()+"消费商品"); } else { TestPC.queue.notify(); } } } } } //测试类 public class TestPC { public static final int MAX_POOL=10; public static final int MAX_PRODUCER=5; public static final int MAX_CONSUMER=4; public static Queue<Goods> queue=new ArrayBlockingQueue<>(MAX_POOL); public static void main(String[] args) { Producer producer=new Producer(); Consumer consumer=new Consumer(); for(int i=0;i<MAX_PRODUCER;i++) { Thread threadA = new Thread(producer, "生产者线程"+i); threadA.start(); } for(int j=0;j<MAX_CONSUMER;j++) { Thread threadB = new Thread(consumer, "消费者线程"+j); threadB.start(); } } }