读书人

java线程系列-行列ArrayBlockingQueue

发布时间: 2012-07-29 15:26:14 作者: rapoo

java线程系列---队列ArrayBlockingQueue

该接口定义了 put 和 take 的阻塞版本,这些不同的类覆盖了生产者-使用者、消息传递、并行任务执行和相关并发设计的大多数常见使用的上下文。

例子:利用队列来实现主线程先执行10次,然后子线程执行50次,依次循环下去

public class BlockingQueueCommunication {

public static void main(String[] args) {

final Business business = new Business();
new Thread(
new Runnable() {

@Override
public void run() {

for(int i=1;i<=50;i++){
business.sub(i);
}

}
}
).start();

for(int i=1;i<=50;i++){
business.main(i);
}

}


static class Business {


BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);//该队列只能存放一个数据
BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);//该队列只能存放一个数据

{
try {
System.out.println("xxxxxdfsdsafdsa");
queue2.put(1); //队列初始化
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void sub(int i){
try {
queue1.put(1); //队列中开始放数据
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int j=1;j<=10;j++){
System.out.println("sub thread sequece of " + j + ",loop of " + i);
}
try {
queue2.take(); //队列中取数据
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void main(int i){
try {
queue2.put(1); //因为队列2中已有数据,所以此处阻塞,等待数据取出,才能放数据
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(int j=1;j<=100;j++){
System.out.println("main thread sequece of " + j + ",loop of " + i);
}
try {
queue1.take(); //队列中取数据
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


}

读书人网 >编程

热点推荐