当前位置:网站首页>Blocking queue example
Blocking queue example
2022-06-30 04:22:00 【No bug program yuan】

Threads trying to get elements from an empty blocking queue will be blocked , Until other threads insert new elements into the empty queue . Again ·
Threads trying to add new elements to the full blocking queue will also be blocked , Until other threads remove one or more elements from the column or clear the queue completely, the queue will be idle again and added later 

Throw an exception : add,remove Method , If the queue is full add, If the queue is empty remove Throw an exception
public static void main(String[] args) {
BlockingQueue<String> blockingQueue=new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
// use add Method if it exceeds the predefined 3 Elements will throw exceptions
System.out.println(blockingQueue.add("x"));
}
// Execution results
true
true
true
Exception in thread "main" java.lang.IllegalStateException: Queue full
at java.util.AbstractQueue.add(AbstractQueue.java:98)
at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
at com.hy.controller.ResController.main(ResController.java:942)Special values
public static void main(String[] args) {
BlockingQueue<String> blockingQueue=new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
// use offer Method if it exceeds the predefined 3 Elements will return false
System.out.println(blockingQueue.offer("x"));
// Returns the queue header element
System.out.println(blockingQueue.peek());
// use poll Method Get the element from the empty blocking queue and return null
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
// Execution results
true
true
true
false
a
a
b
c
nullBlocking :

Overtime :
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> blockingQueue=new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a",2, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("b",2, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("c",2, TimeUnit.SECONDS));
// use offer Method if it exceeds the predefined 3 Elements will return false
System.out.println(" Wait two seconds ===============");
System.out.println(blockingQueue.offer("x",2, TimeUnit.SECONDS));
}
// Execution results
true
true
true
Wait two seconds ===============
false SynchronousQueue: No capacity . The synchronization queue has no capacity .
And others BlockingQueue Different ,SynchronousQueue It's a... That doesn't store elements BlockingQuege.
every last put The operation must wait for one take operation , Otherwise, you can't continue to add elements , vice versa .
Sample code :
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> blockingQueue=new SynchronousQueue<>();
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"\tput 1");
blockingQueue.put("1");
System.out.println(Thread.currentThread().getName()+"\tput 2");
blockingQueue.put("2");
System.out.println(Thread.currentThread().getName()+"\tput 3");
blockingQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t1").start();
new Thread(()->{
try {
Thread.sleep(5);
System.out.println(Thread.currentThread().getName()+"\t Take out :"+blockingQueue.take());
Thread.sleep(5);
System.out.println(Thread.currentThread().getName()+"\t Take out :"+blockingQueue.take());
Thread.sleep(5);
System.out.println(Thread.currentThread().getName()+"\t Take out :"+blockingQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t2").start();
}
// Execution results
t1 put 1
t2 Take out :1
t1 put 2
t2 Take out :2
t1 put 3
t2 Take out :3 topic Objective : A variable with an initial value of zero , Two threads operate on it alternately , One plus 1, One minus 1
Prevent false wake-up mechanism
Sample code :
class ShareData{
private int number=0;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
public void increment() {
lock.lock();
try {
//1 Judge use while no need if , To avoid false awakening
while (number!=0){
//2 wait for , Unable to produce
condition.await();
}
//2 work
number++;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 Notification wake up
condition.signalAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void dncrement() {
lock.lock();
try {
//1 Judge
while (number==0){
//2 wait for , Unable to produce
condition.await();
}
//2 work
number--;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 Notification wake up
condition.signalAll();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
// Execution results
aa 1
bb 0
aa 1
bb 0
aa 1
bb 0
aa 1
bb 0
aa 1
bb 0边栏推荐
- Clients accessing the daytime service (TCP)
- Es2019 key summary
- Project safety and quality
- 工程安全和工程质量
- The same node code will cause duplicate data
- Myrpc version 6
- 【WEBRTC】ADM: rtc_ include_ internal_ audio_ Device triggers RTC_ Dcheck (ADM) assertion
- mysql更新数组形式的json串
- Thinkphp5 implements import function
- MySQL updates JSON string in array form
猜你喜欢

How the FortiGate firewall rejects a port by using the local in policy policy

《机器人SLAM导航核心技术与实战》第1季:第0章_SLAM发展综述

With the deep integration of cloud platform, the "Xueba" objectscale in the object storage industry is coming

技术分享| 融合调度中的广播功能设计

基于SSM框架茶叶商城系统【项目源码+数据库脚本+报告】

The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database

FortiGate firewall quick initialization administrator password

Myrpc version 1

Redis cache avalanche, breakdown and penetration

el-upload上传文件(手动上传,自动上传,上传进度)
随机推荐
【WEBRTC】ADM: rtc_include_internal_audio_device 触发 RTC_DCHECK(adm) 断言
[Thesis reading | deep reading] role2vec:role based graph embeddings
Myrpc version 2
Sql语句遇到的错误,求解
Pig-Latin (UVA492)
Blue Bridge Cup: magic cube rotation [Vocational group]
base64.c
el-upload上傳文件(手動上傳,自動上傳,上傳進度)
Detailed explanation of network layer
数据链路层详解
尝试链接数据库时出现链接超时报错,如何解决?
Splicing strings with custom functions
两个月拿到N个offer,什么难搞的面试官在我这里都不算事
《机器人SLAM导航核心技术与实战》第1季:第0章_SLAM发展综述
Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain
Unity 在编辑器中输入字符串时,转义字符的输入
JS static method
How the FortiGate firewall rejects a port by using the local in policy policy
OneNote software
SQL error caused by entity class: Oracle "ora-00904" error: possible case of invalid identifier