zoukankan      html  css  js  c++  java
  • 阻塞队列-生产者与消费者模式

    public class PC {
    
    
        public static void main(String[] args) {
            BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(5);
    
            for(int i = 0 ;i < 4 ; i ++){
                new Thread(new Productor(bq)).start();
                new Thread(new Consumer(bq)).start();
            }
        }
    
    
    
    }
    package com._ThreadPool._3;
    
    import java.util.Random;
    import java.util.concurrent.BlockingQueue;
    
    public class Productor implements Runnable{
        private BlockingQueue<Integer> bq;
    
        public Productor(BlockingQueue<Integer> bq){
            this.bq = bq;
        }
    
        @Override
        public void run() {
            int i = 0 ;
            while(true){
                try {
                    Thread.sleep(new Random().nextInt(5000));
                    bq.put(i);
                    System.out.println("队列中放入" + i + "队列中还有" + bq.size() + "个元素");
                    i++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    package com._ThreadPool._3;
    
    import java.util.Random;
    import java.util.concurrent.BlockingQueue;
    
    public class Consumer implements Runnable{
        private BlockingQueue<Integer> bq;
    
        public Consumer(BlockingQueue<Integer> bq){
            this.bq = bq;
        }
        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(new Random().nextInt(5000));
                    Integer integer = bq.take();
                    System.out.println("取出了" + integer +",队列里面还有" + bq.size() + "");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 相关阅读:
    Go源码文件与命令
    K8s控制器
    odoo 在form视图sheet右上角增加按钮
    odoo 常用widget
    odoo tree视图中实现横向滚动条
    可能是智障的高二生活
    千题计划
    闲谈
    线性代数与simplex
    好题集锦
  • 原文地址:https://www.cnblogs.com/da-peng/p/9830759.html
Copyright © 2011-2022 走看看