阻塞队列的特点:当队列元素已满的时候,阻塞插入操作;
当队列元素为空的时候,阻塞获取操作;
生产者线程:Producer
1 package test7; 2 3 import java.util.concurrent.BlockingQueue; 4 5 public class Producer implements Runnable{ 6 7 private final BlockingQueue queue; 8 public Producer(BlockingQueue queue){ 9 this.queue=queue; 10 } 11 @Override 12 public void run() { 13 for(int i=1;i<5;i++){ 14 try { 15 System.out.println("正在生产第-"+i+"-个产品"); 16 queue.put(i); 17 } catch (InterruptedException ex) { 18 ex.printStackTrace(); 19 } 20 } 21 } 22 23 }
消费者线程:Consumer
1 package test7; 2 3 import java.util.concurrent.BlockingQueue; 4 5 public class Consumer implements Runnable{ 6 7 private final BlockingQueue queue; 8 public Consumer(BlockingQueue queue){ 9 this.queue=queue; 10 } 11 @Override 12 public void run() { 13 while(true){ 14 try { 15 System.out.println("正在消费第-"+queue.take()+"-个产品"); 16 } catch (InterruptedException ex) { 17 ex.printStackTrace(); 18 } 19 } 20 } 21 22 }
运行:
1 package test7; 2 3 import java.util.concurrent.BlockingQueue; 4 import java.util.concurrent.LinkedBlockingQueue; 5 6 public class Run { 7 8 public static void main(String[] args) { 9 BlockingQueue queue = new LinkedBlockingQueue(); 10 Producer p=new Producer(queue); 11 Consumer c=new Consumer(queue); 12 13 Thread productThread =new Thread(p); 14 Thread consumeThread =new Thread(c); 15 productThread.start(); 16 consumeThread.start(); 17 } 18 }
结果:
正在生产第-1-个产品 正在生产第-2-个产品 正在生产第-3-个产品 正在消费第-1-个产品 正在消费第-2-个产品 正在消费第-3-个产品 正在生产第-4-个产品 正在消费第-4-个产品
时间: 2024-10-08 12:50:50