zoukankan      html  css  js  c++  java
  • 9_1_Java实现的BlockingQueue队列

    package com.nowcoder;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.SpringApplicationConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    
    /**
     * Created by Administrator on 2017/5/9.
     */
    public class MyThread {
    
        class Producer implements Runnable{
            private BlockingQueue<String> p;
    
            public Producer(BlockingQueue p){
                this.p = p;
            }
    
    
            @Override
            public void run() {
    
                try {
                    for (int i = 0; i < 10; i++){
                        Thread.sleep(1000);
                        p.put(String.valueOf(i));
                    }
                }catch (Exception e){
                        e.printStackTrace();
                }
            }
        }
    
        class Consumer implements Runnable{
    
            private BlockingQueue<String> c;
    
            public Consumer(BlockingQueue c){
                this.c = c;
            }
    
            @Override
            public void run() {
                while (true){
                    try {
                        System.out.println(Thread.currentThread().getName() +":" + c.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
    
            }
        }
    
        public void testBlockingQueue(){
            BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(10);
            new Thread(new Producer(blockingQueue)).start();
            new Thread(new Consumer(blockingQueue), "consumer1").start();
            new Thread(new Consumer(blockingQueue), "consumer2").start();
    
        }
    
        public static void main(String[] args){
            new MyThread().testBlockingQueue();
        }
    
    
    
    
    
    
    
    
    
    
    }
  • 相关阅读:
    centos7配置java环境
    puppet使用 apache passsenger 作为前端 (debian)
    puppet 和 apache passenger的配置
    puppet 安装
    JQuery Plugin 开发
    Shell脚本中的 测试开关 和 特殊参数
    CPPUTest 单元测试框架(针对 C 单元测试的使用说明)
    Makefile 使用总结
    挂载KVM Guest操作系统磁盘
    Linux资源管理-IO优先级
  • 原文地址:https://www.cnblogs.com/noaman/p/6833163.html
Copyright © 2011-2022 走看看