阻塞队列案例分享

<code>import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class BlockingQueueTest {public static void main(String[] args) {final BlockingQueue queue = new ArrayBlockingQueue(3);for(int i=0;i<2;i++){new Thread(){public void run(){while(true){try {Thread.sleep((long)(Math.random()*1000));System.out.println(Thread.currentThread().getName() + "准备放数据!");queue.put(1);System.out.println(Thread.currentThread().getName() + "已经放了数据," + "队列目前有" + queue.size() + "个数据");} catch (InterruptedException e) {e.printStackTrace();}}}}.start();}new Thread(){public void run(){while(true){try {//将此处的睡眠时间分别改为100和1000,观察运行结果Thread.sleep(1000);System.out.println(Thread.currentThread().getName() + "准备取数据!");queue.take();System.out.println(Thread.currentThread().getName() + "已经取走数据," + "队列目前有" + queue.size() + "个数据");} catch (InterruptedException e) {e.printStackTrace();}}}}.start();}}/<code>

运行结果如下图所示:

阻塞队列案例分享

阻塞队列的运用

<code>package com.chang;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class BlockQueueThreadComunication {/** * @param args */public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable() {@Overridepublic void run() {for(int i=1;i<=50;i++){business.sub(i);}}}).start();for(int i=1;i<=50;i++){business.main(i);}}//如果一个内部类用static修饰,那么这个内部类将会变成外部类static class Business {    BlockingQueue<integer>  queue1= new ArrayBlockingQueue<integer>(1);  BlockingQueue<integer>  queue2 =  new ArrayBlockingQueue<integer>(1);    //匿名构造方法, 创建几个对象,就会被调用几次, 而静态代码块只会被调用一次  {  try {queue2.put(1);} catch (InterruptedException e) {e.printStackTrace();}  }      public  void sub(int i){    try {queue1.put(1);} catch (InterruptedException e) {e.printStackTrace();}for(int j=1;j<=10;j++){System.out.println("sub thread sequence of " + j + ",loop of " + i);}try {queue2.take();} catch (InterruptedException e) {e.printStackTrace();}  }    public  void main(int i){  try {queue2.put(1);} catch (InterruptedException e) {e.printStackTrace();}for(int j=1;j<=100;j++){System.out.println("main thread sequence of " + j + ",loop of " + i);}try {queue1.take();} catch (InterruptedException e) {e.printStackTrace();}  }  }}/<integer>/<integer>/<integer>/<integer>/<code>


分享到:


相關文章: