当前位置:网站首页>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
null
Blocking :
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
边栏推荐
猜你喜欢
Redis sentry, persistence, master-slave, hand tear LRU
Error encountered in SQL statement, solve
el-upload上傳文件(手動上傳,自動上傳,上傳進度)
An error occurs when sqlyog imports the database. Please help solve it!
The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure
Machine learning notes
Junior students summarize JS basic interview questions
Redis cache avalanche, breakdown and penetration
Blue Bridge Cup: magic cube rotation [Vocational group]
技术分享| 融合调度中的广播功能设计
随机推荐
Cloud native -- websocket of Web real-time communication technology
Five methods to clear floating and their advantages and disadvantages
Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0
FortiGate firewall modifies the default timeout of a session
Error Nova missingauthplugin: an auth plugin is required to determine endpoint URL
Myrpc version 4
Idea grey screen problem
Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool
第九天 脚本与资源管理
尝试链接数据库时出现链接超时报错,如何解决?
MySQL updates JSON string in array form
Anonymous pipeline for interprocess communication
Day 10 data saving and loading
JS deconstruction assignment
Robot slam navigation core technology and practice Season 1: Chapter 0_ Slam development overview
487-3279(POJ1002)
Errno and PERROR
Day 12 advanced programming techniques
JS proxy
2021-07-14