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();
                }
            }
        }
    }
  • 相关阅读:
    python 多线程测试
    python 多线程join()
    python 多线程 t.setDaemon(True):
    线程锁
    python 多线程
    模板渲染和参数传递.
    求两个数组的交集
    java数组并集/交集/差集(补集)
    java各种集合的线程安全
    页面跳转和重定向
  • 原文地址:https://www.cnblogs.com/da-peng/p/9830759.html
Copyright © 2011-2022 走看看