线程安全8 - 可阻塞的队列
作者:
小超_8b2f | 来源:发表于
2019-09-29 11:06 被阅读0次
- 队列包含固定长度的队列和不固定长度的队列
- 什么是阻塞队列,阻塞队列的作用与实际应用,阻塞队列的实现原理
- ArrayBlockingQueue
- 看BlockingQueue类的帮助文档,其中有各个方法的区别对比表格
- 只有put方法和take方法才具有阻塞功能
- 用3个空间的队列来演示阻塞队列的功能和效果。
- 用2个只有一个空间的队列来实现同步通知的功能
- 阻塞队列与Semaphore类似,但也不同,阻塞队列是一方存放数据,另一方释放数据,Semaphore通常则是由同一方设置和释放信号量
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockQueueTest {
public static void main(String[] args) {
final Business3 business = new Business3();
new Thread(new Runnable() {
@Override
public void run() {
//子线程循环调用50次某逻辑
for(int i = 0; i < 50; i++) {
business.sub(i);
}
}
}).start();
//主线程循环调用50次某逻辑
for(int i = 0; i < 50; i++) {
business.main(i);
}
}
}
class Business3 {
BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<>(1);
BlockingQueue<Integer> queue2 = new ArrayBlockingQueue<>(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 = 0; j < 10; j++)
System.out.println("sub Thread run 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 e) {
e.printStackTrace();
}
for (int j = 0; j < 10; j++)
System.out.println("main Thread run sequece of " + j + " loop of " + i);
try {
queue1.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
本文标题:线程安全8 - 可阻塞的队列
本文链接:https://www.haomeiwen.com/subject/nlacyctx.html
网友评论