标签:string 消费者 sem ati except 生产者消费者 override ide try
package javalearn; import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { private static final int MAX = 5; ///////////////生产者 public static class Producer extends Thread{ private Queue<Integer> queue; int i=0; String name; int max; public Producer(Queue<Integer> queue,String name,int max){ super(name); this.queue = queue; this.name = name; this.max = max; } @Override public void run() { while (true){ synchronized(queue){ while (queue.size()==max){ //停产 自旋,防止出现虚假唤醒 try { queue.wait(); }catch (Exception e){ e.printStackTrace(); } } //继续生产 queue.offer(i++); queue.notifyAll(); } } } } ///////////////消费者 public static class Consumer extends Thread{ private Queue<Integer> queue; String name; public Consumer(Queue<Integer>queue,String name){ super(name); this.name = name; this.queue = queue; } @Override public void run() { while (true){ synchronized(queue){ while (queue.isEmpty()){ //空了就要停 try { queue.wait(); }catch (Exception e){ e.printStackTrace(); } } queue.poll(); queue.notifyAll(); } } } } public static void main(String[] args){ Queue<Integer>queue = new LinkedList<>(); Thread producer1 = new Producer(queue,"P-1",MAX); Thread producer2 = new Producer(queue,"P-2",MAX); Thread consumer1 = new Consumer(queue,"C-1"); Thread consumer2 = new Consumer(queue,"C-2"); producer1.start(); producer2.start(); consumer1.start(); consumer2.start(); } }
标签:string 消费者 sem ati except 生产者消费者 override ide try
原文地址:https://www.cnblogs.com/zheng123/p/11187976.html