当前位置:网站首页>Use and principle of wait notify
Use and principle of wait notify
2022-07-01 05:09:00 【People below two meters are mortals】
List of articles
1、API Introduce
- obj.wait() Let in object Monitor thread to waitSet wait for
- obj.wait(long timeout) Let in object Monitor thread to waitSet wait for , But there will be a time limit , No unlimited waiting
- obj.notify() stay object It's going on waitSet Pick one of the waiting threads to wake up
- obj.notifyAll() Give Way object It's going on waitSet All the waiting threads wake up
They are all means of collaboration between threads , All belong to Object Object method . You must get the lock for this object ( Become Owner), To call these methods
such as :
private final static Object OBJ = new Object();
@SneakyThrows
public static void main(String[] args) {
OBJ.wait();
}

The monitor status that reports an error is abnormal , That is, the current thread has not obtained OBJ lock , perform wait I don't know where to go WaitSet? It should be used in this way
private final static Object OBJ = new Object();
@SneakyThrows
public static void main(String[] args) {
synchronized (OBJ) {
OBJ.wait();
}
}
Example
private final static Object OBJ = new Object();
@SneakyThrows
public static void main(String[] args) {
new Thread(() -> {
synchronized (OBJ) {
log.info(" perform ....");
try {
OBJ.wait(); // Let the thread in OBJ Keep waiting on
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("t1 Other code ....");
}
}, "t1").start();
new Thread(() -> {
synchronized (OBJ) {
log.info(" perform ....");
try {
OBJ.wait(); // Let the thread in OBJ Keep waiting on
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("t2 Other code ....");
}
}, "t2").start();
// The main thread executes in two seconds
TimeUnit.SECONDS.sleep(2);
log.info(" Wake up the OBJ On other threads ");
synchronized (OBJ) {
OBJ.notify(); // Wake up the OBJ Last thread
}
}

You can find ,notify You can only wake up at a time WaitSet The random one in , If necessary t1 and t2 Wake up at the same time , have access to notiyAll, Will all WaitSet The threads in all wake up
2、 principle
Review the following diagram

- Owner Thread discovery condition not met , call wait Method , You can enter WaitSet Turn into WAITING state
- BLOCKED and WAITING All threads are blocked , Not occupy CPU Time slice
- BLOCKED Thread will be Owner Wake up when thread releases lock
- WAITING Thread will be Owner Thread calls notify or notifyAll Wake up when , But waking up doesn't mean the person gets the lock immediately , Still need to enter EntryList Re compete
3、wait and sleep The difference between
- sleep yes Thread Method , and wait yes Object Methods
- sleep There's no need to force and synchronized In combination with , but wait Need and synchronized Together with
- sleep While sleeping , Object locks will not be released , but wait The object lock is released while waiting
- Their states are TIMED_WAITING
4、 Use posture correctly
Here we simulate a scene , Now there is a studio ( lock ), There is a man, Xiao Nan , He has a lot of problems , It must have smoke to work , Let's make it happen
static final Object ROOM = new Object();
static boolean hasCigarette = false;
@SneakyThrows
public static void main(String[] args) {
new Thread(() -> {
synchronized (ROOM) {
log.info(" Do you have any cigarettes ?[{}]", hasCigarette);
if (!hasCigarette) {
log.info(" No smoke , Take a break !");
try {
ROOM.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(" Do you have any cigarettes ?[{}]", hasCigarette);
if (hasCigarette) {
log.info(" You can start working ");
}
}
}, " Xiaonan ").start();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
synchronized (ROOM) {
log.info(" You can start working ");
}
}, " Other people ").start();
}
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
synchronized (ROOM) {
ROOM.notify();
hasCigarette = true;
log.info(" Here comes the smoke !");
}
}, " The cigarette man ").start();
}

But there is still a problem with the current program , If there are other threads wait What shall I do? ? It is not easy to wake up the wrong thread ( spurious wakeup )? such as , Now there is another man named little girl , She's strange, too , Only when the takeout arrives can he work
static final Object ROOM = new Object();
static boolean hasCigarette = false;
static boolean hasTakeout = false;
@SneakyThrows
public static void main(String[] args) {
new Thread(() -> {
synchronized (ROOM) {
log.info(" Do you have any cigarettes ?[{}]", hasCigarette);
if (!hasCigarette) {
log.info(" No smoke , Take a break !");
try {
ROOM.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(" Do you have any cigarettes ?[{}]", hasCigarette);
if (hasCigarette) {
log.info(" You can start working ");
} else {
log.info(" Didn't do it ...");
}
}
}, " Xiaonan ").start();
new Thread(() -> {
synchronized (ROOM) {
Thread thread = Thread.currentThread();
log.info(" Did the takeout arrive ?[{}]", hasTakeout);
if (!hasTakeout) {
log.info(" No takeout , Take a break !");
try {
ROOM.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(" Did the takeout arrive ?[{}]", hasTakeout);
if (hasTakeout) {
log.info(" You can start working ");
} else {
log.info(" Didn't do it ...");
}
}
}, " Little girl ").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
synchronized (ROOM) {
hasTakeout = true;
log.info(" Here's the takeout !");
ROOM.notify();
}
}, " Take away delivery ").start();
}

In order to solve the false awakening , As a result, the correct thread is not awakened , We can try it notifyAll , In this way, the correct target thread must be awakened , But it will also wake up the threads that should not be awakened , So at this time , We can try it while Loop to determine whether it is an effective wake-up , Otherwise again wait
static final Object ROOM = new Object();
static boolean hasCigarette = false;
static boolean hasTakeout = false;
@SneakyThrows
public static void main(String[] args) {
new Thread(() -> {
synchronized (ROOM) {
log.info(" Do you have any cigarettes ?[{}]", hasCigarette);
while (!hasCigarette) {
log.info(" No smoke , Take a break !");
try {
ROOM.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(" Do you have any cigarettes ?[{}]", hasCigarette);
if (hasCigarette) {
log.info(" You can start working ");
} else {
log.info(" Didn't do it ...");
}
}
}, " Xiaonan ").start();
new Thread(() -> {
synchronized (ROOM) {
log.info(" Did the takeout arrive ?[{}]", hasTakeout);
while (!hasTakeout) {
log.info(" No takeout , Take a break !");
try {
ROOM.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.info(" Did the takeout arrive ?[{}]", hasTakeout);
if (hasTakeout) {
log.info(" You can start working ");
} else {
log.info(" Didn't do it ...");
}
}
}, " Little girl ").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
synchronized (ROOM) {
hasTakeout = true;
log.info(" Here's the takeout !");
ROOM.notifyAll();
}
}, " Take away delivery ").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
synchronized (ROOM) {
ROOM.notify();
hasCigarette = true;
log.info(" Here comes the smoke !");
}
}, " The cigarette man ").start();
}

So the correct use of templates should be
synchronized(lock) {
while( Conditions not established ) {
lock.wait();
}
// work
}
// Another thread
synchronized(lock) {
lock.notifyAll();
}
边栏推荐
- 复制宝贝提示材质不能为空,如何解决?
- 数字金额加逗号;js给数字加三位一逗号间隔的两种方法;js数据格式化
- Youqitong [vip] v3.7.2022.0106 official January 22 Edition
- Principle, technology and implementation scheme of data consistency in distributed database
- 缓冲流与转换流
- Leetcode316- remove duplicate letters - stack - greedy - string
- 解决:拖动xib控件到代码文件中,报错setValue:forUndefinedKey:this class is not key value coding-compliant for the key
- Query long transaction
- What can the points mall Games bring to businesses? How to build a points mall?
- [summer daily question] Luogu p5886 Hello, 2020!
猜你喜欢

Neural networks - use sequential to build neural networks

Basic skeleton of neural network nn Use of moudle

LevelDB源码分析之LRU Cache

Oracle views the creation time of the tablespace in the database

Causes of short circuit of conductive slip ring and Countermeasures

How to select conductive slip ring material
![解决:Thread 1:[<*>setValue:forUndefinedKey]:this class is not key value coding-compliant for the key *](/img/88/0b99d1db2cdc70ab72d2b3c623dfaa.jpg)
解决:Thread 1:[<*>setValue:forUndefinedKey]:this class is not key value coding-compliant for the key *

【暑期每日一题】洛谷 P5886 Hello, 2020!

Explanation of characteristics of hydraulic slip ring

工业导电滑环的应用
随机推荐
Neural networks - use of maximum pooling
Vmware workstation network card settings and three common network modes
手动实现一个简单的栈
Spanner 论文小结
Neural network - nonlinear activation
LeetCode_ 28 (implement strstr())
【暑期每日一题】洛谷 P1568 赛跑
How to hide browser network IP address and modify IP internet access?
【暑期每日一题】洛谷 P2026 求一次函数解析式
【暑期每日一题】洛谷 P5886 Hello, 2020!
Common methods in transforms
Global and Chinese market of metal oxide semiconductor field effect transistors 2022-2028: Research Report on technology, participants, trends, market size and share
Pytoch (I) -- basic grammar
打印流与System.setout();
【暑期每日一题】洛谷 P7222 [RC-04] 信息学竞赛
Distributed architecture system splitting principles, requirements and microservice splitting steps
Distributed transactions - Solutions
Pytorch neural network construction template
Tcp/ip explanation (version 2) notes / 3 link layer / 3.2 Ethernet and IEEE 802 lan/man standards
【暑期每日一题】洛谷 P5740【深基7.例9】最厉害的学生