9_1_Java实现的BlockingQueue队列

Posted noaman_wgs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    }










}

 

以上是关于9_1_Java实现的BlockingQueue队列的主要内容,如果未能解决你的问题,请参考以下文章

Java BlockingQueue阻塞队列

24_BlockingQueue接口

阻塞队列(BlockingQueue)

16_Queue_利用wait()和notify()编写一个阻塞队列

C++ 等价于 Java 的 BlockingQueue

Java线程和多线程——BlockingQueue