专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > 软件架构设计

堵塞队列的应用

发布时间:2011-06-20 02:10:50 文章来源:www.iduyao.cn 采编人员:星星草
阻塞队列的应用

之前的一篇代码说的是阻塞队列的原理实现,现在是直接使用java封装好的阻塞队列的类。比如要实现线程同步通信,子线程循环10次,再到主线程循环100次,如此循环五十次,用阻塞队列来实现代码如下:


 

package com.thread.test6;

import java.util.concurrent.ArrayBlockingQueue;



/**

 * @fileName BlockingQueueCommunication.java

 * @description 阻塞队列的应用,子线程循环10次,接着主线程循环100次,

 * 接着又回到子线程循环10次,接着再回到主线程又循环100次,

 * 如此循环50次

 * @date 2012-6-19

 * @time 21:50

 * @author wst

 */

public class BlockingQueueCommunication {


public static void main(String[] args) {

final Business b=new Business();

//子线程

new Thread(new Runnable(){

@Override

public void run() {

for(int i=1;i<=50;i++){

b.sub(i);

}

}

}).start();

//主线程

for(int i=1;i<=50;i++){

b.main(i);

}

}


static class Business{

ArrayBlockingQueue<Integer> abq1 = new ArrayBlockingQueue<Integer>(1);

ArrayBlockingQueue<Integer> abq2 = new ArrayBlockingQueue<Integer>(1);

{

/*

* 内部匿名构造方法,总是在显性构造方法执行前执行

*/

try {

abq2.put(1);//队列2放数据

} catch (InterruptedException e) {

e.printStackTrace();

}

}

//子线程循环10次

public void sub(int i){

try {

abq1.put(1);//队列1放

for(int j=1;j<=10;j++){

System.out.println("sub j="+j+"  i="+i);

}

abq2.take();//队列2取,取后队列2可放,即到main执行

} catch (InterruptedException e) {

e.printStackTrace();

}

}

//主线程循环100次

public void main(int i){

try {

abq2.put(1);//队列2放

for(int j=1;j<=100;j++){

System.out.println("main j="+j+"  i="+i);

}

abq1.take();//队列1取,此时队列1可以放,即又到sub执行

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}


 

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: