当前位置:网站首页>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
边栏推荐
猜你喜欢

机器学习——主成分分析(PCA)

SVG+js拖拽滑块圆形进度条

Status of the thread pool

希尔排序图文详解+代码实现

分布式事务原理以及解决分布式事务方案

Uniapp develops wechat official account, and the drop-down box selects the first one in the list by default

解决Deprecated: Methods with the same name as their class will not be constructors in报错方案

百度网盘下载一直请求中问题解决

canvas管道动画js特效

6.套餐管理业务开发
随机推荐
Go language development environment setup +goland configuration under the latest Windows
2022-06-23:给定一个非负数组,任意选择数字,使累加和最大且为7的倍数,返回最大累加和。 n比较大,10的5次方。 来自美团。3.26笔试。
Using pandas to read SQL server data table
Six states of threads
23. Opencv——图像拼接项目
简单的价格表样式代码
Graffiti smart brings a variety of heavy smart lighting solutions to the 2022 American International Lighting Exhibition
Why is JSX syntax so popular?
[input method] so far, there are so many Chinese character input methods!
411 stack and queue (20. valid parentheses, 1047. delete all adjacent duplicates in the string, 150. inverse Polish expression evaluation, 239. sliding window maximum, 347. the first k high-frequency
Recursive traversal of 414 binary tree
Leetcode - 498: traversée diagonale
2.登陆退出功能开发
Floating point notation (summarized from cs61c and CMU CSAPP)
线程池的执行流程
分布式事务原理以及解决分布式事务方案
图解杂项【防止丢失进行存档用的】
numpy. logical_ or
Error reading CSV (TSV) file
牛客-TOP101-BM28