Java 多线程应用 之 ArrayBlockingQueue

来源:互联网 发布:淘宝鞋店简介 编辑:程序博客网 时间:2024/05/14 02:23

ArrayBlockingQueue,顾名思义是阻塞队列,通过设定队列的最大容量开来达到控制最多允许几条线程再同时运行。还有几个类也可以达到相同的效果。这是几个月前看了下Java多线程应用的教程,好像是张孝祥的,翻到了之前写的代码就贴出来。

import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class BlockingQueueCommunication {public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable() {public void run() {for (int i = 1; i <= 4; i++) {business.sub(i);}}}).start();new Thread(new Runnable() {public void run() {for (int i = 1; i <= 4; i++) {business.main(i);}}}).start();}// 说明:在这个静态类里定义两个阻塞队列,容量是1,来实现相互通知// 需要开始往队列1放东西,同时队列2是阻塞的,那么就需要初始化时往队列2中放东西,让其阻塞// 往队列1中放完东西后它会阻塞,执行完这个方法之前要让队列2中的东西取走,让其不阻塞,然后就可以执行队列2下面的代码// 同样道理,在队列2所在的方法执行完之前要取走队列1中的东西,让队列1不阻塞。这样就实现了你一下我一下交替执行代码static class Business {BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);// 构造块,{try {System.out.println("实例初始化时往队列2种put一下");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 <= 2; j++) {System.out.println("sub thread sequece of " + j + ",loop of "+ i);}try {queue2.take();} catch (InterruptedException e) {e.printStackTrace();}}public void main(int i) {try {queue2.put(1);} catch (InterruptedException e1) {e1.printStackTrace();}for (int j = 1; j <= 3; j++) {System.out.println("main thread sequece of " + j + ",loop of "+ i);}System.out.println();try {queue1.take();} catch (InterruptedException e) {e.printStackTrace();}}}}

运行结果: