当前位置:网站首页>The difference between the sleep () method and the wait () method of a thread
The difference between the sleep () method and the wait () method of a thread
2022-06-24 10:24:00 【Ugly and ugly】
in general , Thread sleep() Methods and wait() Methods have the following differences :
(1)sleep() The method is Thread Methods in class , and wait() The method is Object Methods in class .
(2)sleep() Method will not release lock, however wait() Method will release , And will join the waiting queue .
(3)sleep() Method does not depend on synchronizer synchronized(), however wait() Method Need to rely on synchronized keyword .
(4) Thread calls sleep() You don't need to wake up later ( Start blocking during sleep , The monitoring state of the thread remains , When the specified sleep time is up, it will automatically resume the running state ), however wait() Methods need to be reawakened ( Don't set a time and need to be interrupted by someone else ).
public class SleepDemo {
public static final Object LOCK = new Object();
public static void main(String[] args) {
Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
@Override
public void run() {
new SleepDemo().testSleep();
}
}.start());
}
private void testSleep() {
synchronized (LOCK) {
try {
System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
// Sleep 2 s
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
} catch (Exception e) {
}
}
}
}
You can see , Threads 1 Got the resources first , Sleep is required when executing the main method 2 second , So in these two seconds , Even if the thread 1 There's no movement , Threads 2 Nor can it preempt resources . It should be noted that , Calling sleep() When the method is used , If there are two threads , To achieve the effect of thread sleep, you need to use synchronized() Method , Otherwise, the effect will not be achieved .
public class SleepDemo {
// public static final Object LOCK = new Object();
public static void main(String[] args) {
Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
@Override
public void run() {
new SleepDemo().testSleep();
}
}.start());
}
private void testSleep() {
// synchronized (LOCK) {
try {
System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
// Sleep 2 s
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
} catch (Exception e) {
System.out.println(e);
}
// }
}
}

As shown above , Don't use synchronized() Two threads will execute at the same time , Simultaneous sleep , At the same time, the execution is resumed .
Thus we can see that , call sleep() When the method is used , Is not strongly dependent on synchronized() Method , If I have only one thread , So use synchronized() Methods and do not use synchronized() The effect of the method is the same . If there are two threads , You can also choose to use or not use synchronized() Method . however wait() The approach is different ,wait() Methods are strongly dependent on synchronized() Method , If not used synchronized() Method words ,wait() Method will report an error .
public class WaitDemo {
public static final Object LOCK = new Object();
public static void main(String[] args) {
Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
@Override
public void run() {
WaitDemo.testWait();
}
}.start());
}
private static void testWait() {
// synchronized (LOCK) {
try {
System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
// wait for 2 s
LOCK.wait(2000);
System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
// }
}

Use synchronized After keyword modification :
public class WaitDemo {
public static final Object LOCK = new Object();
public static void main(String[] args) {
Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
@Override
public void run() {
WaitDemo.testWait();
}
}.start());
}
private static void testWait() {
synchronized (LOCK) {
try {
System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
// wait for 2 s
LOCK.wait(2000);
System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
Because it is specified in the code wait(2000), So when 2 Seconds later, the thread will resume execution , Without another thread to wake up , If wait() Method does not specify a time , Then the thread will wait ~
besides , Once a thread is wait after , There must be another thread to wake up , Otherwise, it will be in a waiting state .
public class WaitDemo {
public static final Object LOCK = new Object();
private void testWait1() {
synchronized (LOCK) {
try {
System.out.println(Thread.currentThread().getName() + " Start execution : " + System.currentTimeMillis() / 1000);
LOCK.wait();
System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
} catch (Exception e) {
System.out.println(e);
}
}
}
private void testNotify() {
synchronized (LOCK) {
try {
Thread.sleep(2000);
LOCK.notify();
System.out.println(Thread.currentThread().getName() + " Wake up another thread : " + System.currentTimeMillis() / 1000);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
new WaitDemo().testWait1();
}
}.start();
new Thread() {
@Override
public void run() {
new WaitDemo().testNotify();
}
}.start();
}
}
This article references from :sleep() and wait() Difference analysis of - Nuggets
边栏推荐
- Baidu online disk download has been in the process of requesting solutions
- 【Energy Reports期刊发表】2022年能源与环境工程国际会议(CFEEE 2022)
- Floating point notation (summarized from cs61c and CMU CSAPP)
- 1. project environment construction
- The great charm of cookies
- Web site development, lazy image loading
- 记录一下MySql update会锁定哪些范围的数据
- 一群骷髅在飞canvas动画js特效
- SVG+js拖拽滑块圆形进度条
- Cookie encryption 4 RPC method determines cookie encryption
猜你喜欢

Resolved: methods with the same name as their class will not be constructors in

Record the range of data that MySQL update will lock

uniapp实现点击拨打电话功能

Phpstrom code formatting settings

Using pandas to read SQL server data table

Role of message queuing

Six states of threads

【Energy Reports期刊发表】2022年能源与环境工程国际会议(CFEEE 2022)

JMeter接口测试工具基础— 取样器sampler(二)

上升的气泡canvas破碎动画js特效
随机推荐
机器学习——感知机及K近邻
Normal equation
CVPR 2022 oral | NVIDIA proposes an efficient visual transformer network a-vit with adaptive token. The calculation of unimportant tokens can be stopped in advance
SSM integration
JMeter接口测试工具基础— 使用Badboy录制JMeter脚本
Get the QR code of wechat applet with parameters - and share the source code of modifying the QR code logo
leetCode-498: 對角線遍曆
【IEEE出版】2022年服务机器人国际研讨会(IWoSR 2022)
leetCode-929: 独特的电子邮件地址
How to customize sharing links in wechat for H5 web pages
Leetcode-1089: replication zero
Wechat cloud hosting launch public beta: in the appointment of the publicity meeting
The great charm of cookies
Network of test and development - Common Service Protocols
线程池的执行流程
tf.contrib.layers.batch_norm
1.项目环境搭建
24. 图像拼接大作业
How large and medium-sized enterprises build their own monitoring system
Phpstrom code formatting settings