• 阻塞队列实现生产者消费者模式


    阻塞队列的特点:当队列元素已满的时候,阻塞插入操作;

                            当队列元素为空的时候,阻塞获取操作;

    生产者线程: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-个产品
  • 相关阅读:
    Linux系统备份与恢复
    CentOS7修改设置静态IP和DNS
    CentOS系统基础优化16条知识汇总
    CentOS英文提示修改为中文提示的方法
    CentOS修改主机名和网络信息
    CentOS 7系统查看系统版本和机器位数
    Linux下设置SSH Server设置时间链接限制
    查看Linux下系统资源占用常用命令(top、free、uptime)
    查看CentOS系统运行了多久使用uptime命令
    设计模式(七)学习----命令模式
  • 原文地址:https://www.cnblogs.com/noaman/p/6159966.html
Copyright © 2020-2023  润新知