首页 > 代码库 > 9_1_Java实现的BlockingQueue队列
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队列
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。