控制程序依次交替执行的办法之一:
package com.xxx.queue;
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(){
public void run() {
for(int i=0;i<50;i++){
business.sub(i);
}
};
}.start();
for(int i=0;i<50;i++){
business.main(i);
}
}
static class Business{
BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<Integer>(1);
BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<Integer>(1);
{
try {
queue2.put(1);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sub(int i){
try {
queue1.put(1);
} catch (Exception e) {
e.printStackTrace();
}
for(int j=1;j<=10;j++){
System.out.println("sub thread queue of "+j+",loop of"+i);
}
try {
queue2.take();
} catch (Exception e) {
e.printStackTrace();
}
}
public void main(int i){
try {
queue2.put(1);
} catch (Exception e) {
e.printStackTrace();
}
for(int j=1;j<=10;j++){
System.out.println("main thread queue of "+j+",loop of"+i);
}
try {
queue1.take();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
运行程序,打印结果如下:
sub thread queue of 1,loop of 0
sub thread queue of 2,loop of 0
sub thread queue of 3,loop of 0
sub thread queue of 4,loop of 0
sub thread queue of 5,loop of 0
sub thread queue of 6,loop of 0
sub thread queue of 7,loop of 0
sub thread queue of 8,loop of 0
sub thread queue of 9,loop of 0
sub thread queue of 10,loop of 0
main thread queue of 1,loop of 0
main thread queue of 2,loop of 0
main thread queue of 3,loop of 0
main thread queue of 4,loop of 0
main thread queue of 5,loop of 0
main thread queue of 6,loop of 0
main thread queue of 7,loop of 0
main thread queue of 8,loop of 0
main thread queue of 9,loop of 0
main thread queue of 10,loop of 0
sub thread queue of 1,loop of 1
sub thread queue of 2,loop of 1
sub thread queue of 3,loop of 1
sub thread queue of 4,loop of 1
sub thread queue of 5,loop of 1
sub thread queue of 6,loop of 1
sub thread queue of 7,loop of 1
sub thread queue of 8,loop of 1
sub thread queue of 9,loop of 1
sub thread queue of 10,loop of 1
main thread queue of 1,loop of 1
main thread queue of 2,loop of 1
main thread queue of 3,loop of 1
main thread queue of 4,loop of 1
main thread queue of 5,loop of 1
main thread queue of 6,loop of 1
main thread queue of 7,loop of 1
main thread queue of 8,loop of 1
main thread queue of 9,loop of 1
main thread queue of 10,loop of 1
。。。。。。
打印信息没有贴完,完整结果可以猜想得到 ,后面依次是2,3,4。。。49循环结束。
这里巧妙地利用了阻塞队列的特点:有元素时,可以取出take,没有则等待,因为队列长度固定,只能放一个元素,所以队列满的,就不能插入put了,只能等待取出才能继续插入。
这里Business类的sub,main方法,每次在进行操作之前都做了一个可以执行的操作插入put,操作完成,将另一个队列的元素进行取出take,相当于锁功能的获取锁与释放锁。正好形成了一个互斥的效果,一个可以操作,另一个阻塞等待。