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();
                }
            }
        }
    }
  • 相关阅读:
    password
    bzoj 1458: 士兵占领
    国家集训队2011 happiness
    cogs 2051. 王者之剑
    uva 10779 Collectors Problem
    [Jxoi2012]奇怪的道路
    天神下凡
    藏宝图
    黑红树
    愤怒的小鸟
  • 原文地址:https://www.cnblogs.com/da-peng/p/9830759.html
Copyright © 2011-2022 走看看