今天看了《传智播客_张孝祥_Java多线程与并发库高级应用视频教程》之一,觉得使用BlockingQueue阻塞队列来模拟两个线程之间的通信这个东西很有意思,因为它使用了
BlockingQueue阻塞队列中的put(E o)
void | put(E o) 将指定元素添加到此队列中,如果没有可用空间,将一直等待(如果有必要)。 |
和take()
E | take() 检索并移除此队列的头部,如果此队列不存在任何元素,则一直等待。 |
package cn.yang.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueCommunication {
/**
* 两个线程之间的通信,使用队列的阻塞功能,见queue1和queue2的使用
* @param args
*/
public static void main(String[] args) {
final Business business = new Business();
new Thread(
new Runnable() {
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 {
queue2.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sub(int i){
try {
queue1.put(1);
for(int j=1;j<=10;j++){
System.out.println("sub thread sequence of " + j + ",loop of " + i);
}
queue2.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void main(int i){
try {
queue2.put(1);
for(int j=1;j<=100;j++){
System.out.println("main thread sequence of " + j + ",loop of " + i);
}
queue1.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行效果是:
sub thread sequence of 1,loop of 1
sub thread sequence of 2,loop of 1
sub thread sequence of 3,loop of 1
*
*
*
sub thread sequence of 10,loop of 1
main thread sequence of 1,loop of 1
main thread sequence of 2,loop of 1
main thread sequence of 3,loop of 1
*
*
*
main thread sequence of 99,loop of 1
main thread sequence of 100,loop of 1
sub thread sequence of 1,loop of 2
sub thread sequence of 2,loop of 2
sub thread sequence of 3,loop of 2
*
*
*
sub thread sequence of 10,loop of 2
main thread sequence of 1,loop of 2
main thread sequence of 2,loop of 2
*
*
*
也就是sub(int )与main(int)方法交替执行。
so!The End!
清明前后家家雨咯,看来今天又去不了运动场了
加油!!!!!
2012.4.7