快速实现一个生产者-消费者模型demo
package jesse.test1; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; // 生产者 class Producer implements Runnable{ private BlockingQueue<String> queue; public Producer(BlockingQueue<String> queue) { super(); this.queue = queue; } @Override public void run() { for (int i = 0; i < 20; i++) { try { Thread.sleep(10L); String msg = "msg"+i; System.out.println("Produce new item: "+msg); queue.put(msg); } catch (InterruptedException e) { e.printStackTrace(); } } try { System.out.println("Time to say goodbye"); queue.put(ProducerConsumerModel.EXIT_MSG); } catch (InterruptedException e) { e.printStackTrace(); } } } //消费者 class Consumer implements Runnable{ private BlockingQueue<String> queue; public Consumer(BlockingQueue<String> queue){ this.queue = queue; } @Override public void run() { try { String msg ;
//取值即判断 while(!ProducerConsumerModel.EXIT_MSG.equals(msg=queue.take())){ System.out.println("Consumed item: "+ msg); Thread.sleep(15L); } System.out.println("Exit."); } catch (InterruptedException e) { e.printStackTrace(); } } } public class ProducerConsumerModel { public final static String EXIT_MSG="bye"; public static void main(String[] args) { BlockingQueue<String> queue = new ArrayBlockingQueue<String>(5); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); new Thread(producer).start(); new Thread(consumer).start(); } }