您的位置:首页 > 编程语言 > Java开发

18-java5阻塞队列实现线程间通信-实现线程间通信方式(3)

2015-03-30 05:34 591 查看
一、主要内容

实现子线程运行10次,主线程运行100次,子线程、主线程交替进行,此过程循环进行50次。

二、代码

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<=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);
} catch (InterruptedException e) {
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) {
e.printStackTrace();
}
}

public void main(int i){
try {
queue2.put(1);
} catch (InterruptedException e1) {
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) {
e.printStackTrace();
}
}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐