当前位置:网站首页>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边栏推荐
- Share an example of a simple MapReduce method using a virtual machine
- Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0
- Redis sentry, persistence, master-slave, hand tear LRU
- 第九天 脚本与资源管理
- Find the interface and add parameters to the form
- El upload Upload file (Manual upload, Automatic upload, upload progress)
- FortiGate firewall quick initialization administrator password
- Myrpc version 0
- I spent three years in a big factory outsourcing, which subverted my understanding!
- Machine learning notes
猜你喜欢
![[Thesis reading | deep reading] dane:deep attributed network embedding](/img/c7/60f36c2748b8cd7544b7ef14dc309e.png)
[Thesis reading | deep reading] dane:deep attributed network embedding

Error encountered in SQL statement, solve

Myrpc version 4

Junior students summarize JS basic interview questions

Configure specific source IP in SLA detection of FortiGate sdwan

FortiGate firewall and Aruze cloud tunnel interruption

A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"

第十一天 脚本与游戏AI

lego_loam 代码阅读与总结

el-upload上傳文件(手動上傳,自動上傳,上傳進度)
随机推荐
Refers to the difference between IP and *ip at output
Interface testing -- how to analyze an interface?
Huawei cloud native - data development and datafactory
Named pipes for interprocess communication
基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
各位大佬,flink 1.13.6,mysql-cdc2.2.0,抽取上来的datetime(6)类
Error in conditional filter (if) syntax in sum function in SQL Server2005
Day 10 data saving and loading
Indefinite parameters of JS function
Maya Calendar(POJ1008)
Jour 9 Gestion des scripts et des ressources
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
Error Nova missingauthplugin: an auth plugin is required to determine endpoint URL
FortiGate performs DNAT mapping, and intranet users cannot normally access the mapping
Ora-00907: missing right parenthesis problem supplement
How to solve the problem of link hyperlinks when trying to link the database?
节点CODE相同会导致数据重复
With the deep integration of cloud platform, the "Xueba" objectscale in the object storage industry is coming
Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool
Troubleshooting of abnormal communication between FortiGate and fortiguard cloud