当前位置:网站首页>High paid programmers & interview questions series 63: talk about the differences between sleep (), yield (), join (), and wait ()
High paid programmers & interview questions series 63: talk about the differences between sleep (), yield (), join (), and wait ()
2022-06-30 02:44:00 【11 brother sun】
One . Interview questions and Analysis
1. Interview questions of the day
The way sleep()、yield()、join()、wait() The difference between
2. Problem analysis
Today's topic , It can be said that it is a question we must ask when conducting thread related interviews , Many interviewers look at threads , Would say something ,” say something sleep、yield、join、wait The difference between! “! The reason why this question is asked so frequently , It's not how hard it is , But because these methods are closely related to threads , Understand these methods , At least it means that the applicant is clear about the basic use of threads and the general details . It's like asking an old driver ,” Aoi Sora “ and ” Teacher Wu “ What's the difference? , He must know all about it , Otherwise, it doesn't deserve to be called a ” old hand “!
Then we will follow Yige Let's take a look at the differences between these methods , Of course, if you want to know ” Aoi Sora “ and ” Teacher Wu “ The difference between , Please go out and turn left and go east !
Two . sleep() Method
1. Method introduction
Thread.sleep() yes Thread Class , Can make the current thread sleep , Enter blocking state ( Suspend execution ), If the thread is interrupted in sleep , It will be thrown out. IterruptedException Interrupt exception . When the thread sleep expires, regret to wake up automatically , And return to the runnable state ( Ready state ), Instead of running .sleep() Method API As shown in the figure below :

When this method is used , Be sure to pay attention to where it calls , We In which thread is it called sleep() Method , Which thread will be blocked !
2. Basic use
Understand the basic API After the meaning , Yige Here is an experimental case for you , Learn more about the characteristics of this method .
2.1 Case code
Thread.sleep() The usage code is as follows :
public class ThreadDemo06 {
public static void main(String[] args) {
// Create a worker thread
Thread thread=new Thread(new WorkerThread());
thread.setName("WorkerThread");
thread.start();
// Directly in the main thread sleep
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
try {
// Called in main thread , Blocking main Threads , Sleep 1 Second
//sleep() Method is called in which thread sleep() Method to block which thread .
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Create a worker thread
*/
static class WorkerThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
try {
// The worker thread sleeps for one second
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}2.2 Execution results
The execution result of the above code is as follows :

Be careful , The result of each execution may not be the same ! It needs to be clear here sleep() The call location of the method , If it's in main Call in thread Thread.sleep() Method , It will block main Threads ; If you call... In another thread Thread.sleep() Method , Will block other threads . In addition, the thread will wake up automatically after its sleep expires , And return to the runnable state ( Ready state ), But it's not running . So in the code above ,main Threads execute 1 It will sleep after times 1 Second , Give up CPU The enforcement of ; next WorkerThread Threads execute 1 Time , Then it also sleeps 1 second , It is executed in this order ! However, it is possible for the same thread to execute continuously 2 The next situation !
3. Method features ( a key )
According to the results used above , We can simply sum up Thread.sleep Some characteristics of the method .
- sleep() Method can specify the time of hibernation , However, the actual sleep time of the thread will be greater than or equal to the sleep time ;
- Thread.sleep() Method will force the currently executing thread to sleep ( Suspend execution ), This allows the thread to start from “ Running state ” Turn into “ Blocked state ”;
- In which thread is it called sleep() Method , Which thread will be blocked , namely Only the currently running thread can be controlled ;
- sleep() It's a static method , It is only valid for the current object , Want to ” Object name .sleep()“ It is invalid to put the object thread into sleep in the way of , It will only put the current thread into sleep ;
- The thread will wake up automatically after its sleep expires , And return to the runnable state ( Ready state ), But it's not running ;
- sleep() The specified sleep time is the minimum time that the thread will not run , This method does not guarantee that the thread will start executing after its sleep expires .
4. Description of blocking status
The so-called blocking state , Specific include BLOCKED、WAITING、TIME_WAITING this 3 States ,sleep The status of the post thread is specifically in TIME_WAITING state !
3、 ... and . yield() Method
1. Method introduction
Thread.yield() Method will propose to release CPU Time slice request , Apply for release and preemption CPU Resource opportunities , So that the currently running thread can return to the runnable state , Let other threads with the same priority get the chance to run . But this method does not release the lock , The thread is still in RUNNABLE state . Therefore use yield() Purpose , Is to enable threads with the same priority to rotate among each other . But actually yield() The method cannot guarantee that the goal of concession can be achieved , because CPU Will choose from a large number of threads in the executable state . in other words , The concession thread may be executed again , Other threads are not necessarily selected for execution .
therefore Thread.yield() After method call , It is equivalent to that a thread only applies for transferring the scheduling right to others , As for whether the application is successful , This is JVM The final say . Even if the application is successful , After that, the thread can immediately return to the state of competing thread lock .
It's like having 2 An astronaut with the same ability should perform a flying mission ,A Astronauts have flown over several missions ,B The astronauts never flew once . then A Astronauts apply to the organization , Said to give up the next flight mission to B Well , The probability of this application being successful , But it is also possible that the organization does not agree , Still let A Continue with the next mission .
2. Basic use
2.1 Case code
public class ThreadDemo07 {
public static void main(String[] args) {
MyThread t1 = new MyThread("thread01");
MyThread t2 = new MyThread("thread02");
t1.start();
t2.start();
}
/**
* Create a worker thread
*/
static class MyThread extends Thread {
MyThread(String s) {
super(s);
}
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println(getName() + "--" + i);
if (("thread01").equals(getName())) {
if (i == 5) {
yield();
}
}
}
}
}
}2.2 Execution results

Attention, everyone , The execution result of the above code , Each run may be different . Most of the time ,yield() Method causes the thread to go from running state to runnable state , But it may not work .
3. Method features ( a key )
- yield() The essence of method is to put the current thread back into preemption CPU Time slice ” queue ” in , It just offered to release CPU Application for resources , As for the successful release CPU The right to use the right of JVM decision ;
- perform Thread.yield() After the method , It won't release the lock , The thread is still in RUNNABLE Operational state , The thread will not enter the blocking state ;
- Called yield() After the method , Threads in the RUNNABLE Can run In the state of , Threads reserve the right to be scheduled for execution at any time .
Four . join() Method
1. Method introduction
join() Method is used to add the specified thread to the current thread , Merge two threads that are supposed to execute alternately into threads that execute sequentially .join The bottom layer of the method is by calling wait() Method to achieve waiting , So when a new thread is added , Will leave the main thread waiting (WAITING) state , Wait until the other threads finish executing or are interrupted.
2. Basic use
2.1 Case code
public class ThreadDemo08 {
public static void main(String[] args) {
// Create a Runnable object
Runnable runnable = () -> System.out.println(" Sub thread execution ");
// Turn on 2 Child threads
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
try {
// Start waiting for child threads to join in the main thread ,thread1,thread2
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
// When the main thread executes thread1.join() When the method is used , It is possible to throw an interrupt exception , here , We should pass the interrupt state of the main thread to the child thread ,
// That is to say catch() In the sentence , perform thread1.interrupt() Such a statement ,
// In this way, the sub thread will also be interrupted , This maintains data consistency between multiple threads .
thread1.interrupt();
thread2.interrupt();
}
// Wait for both sub threads to finish executing ( inactive ) 了 , The main thread will execute the following print code
System.out.println(" Main thread execution completed ");
}
}2.2 Execution results

3. Method features ( a key )
- When a new thread is added , Will leave the main thread waiting (WAITING) state , Wait until the other threads are no longer active ;
- The reason why the main thread is waiting , Because join() The underlying call of the method is wait() Method .
5、 ... and . wait() Method
1. Method introduction
wait() The method is Object Object method , When a thread acquires a lock , It is found that there is no condition for execution at present , By calling the wait Method , Enter the waiting state . When the condition is satisfied , It can be called by other threads notify() perhaps notifyAll() Method , To wake up the waiting thread .
There's another one wait(long timeout) Method , This method can pass a time parameter . This is an automatic wake-up mechanism , Within the specified time , If no other thread wakes itself up , Then take the initiative to wake yourself up . If you pass 0 Or not , It means to wait forever .
2. Basic use
2.1 Error case code
Yige First, write an illegal use case for you , This case will produce an exception .
public class ThreadDemo09 {
public static void main(String[] args) {
try {
Object object=new Object();
// Only after obtaining the lock , To call wait() Method , Otherwise, it will occur IllegalMonitorStateException abnormal
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}After the above code is executed , The following exception message will be generated :

So we should pay attention to , Only the thread that has acquired the lock , To call the lock object wait() Method , Otherwise it will throw IllegalMonitorStateException abnormal !
2.2 Correct case code
public class ThreadDemo09 {
public static void main(String[] args) {
// newly build 1 Threads , test wait() Method .
Thread threadA=new Thread(() -> {
//synchronized In brackets ThreadDemo09 class , Indicates that the thread obtains the object lock .
synchronized (ThreadDemo09.class) {
try {
System.out.println(" Threads 1 Start execution ...");
System.out.println(" Threads 1 wait The state before "+Thread.currentThread().getState());
//wait() After method call , The current thread will discard the object lock , That is, the right of execution has been waived , Enters the wait lock pool waiting for this object , At this point the thread is suspended !
ThreadDemo09.class.wait();
System.out.println(" Threads 1 wait The state after "+Thread.currentThread().getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" Threads 1 end of execution !");
}
},"A");
threadA.start();
// Create a second thread
Thread threadB=new Thread(() -> {
synchronized (ThreadDemo09.class) {
System.out.println(" Threads 2 Start execution ...");
//System.out.println(" Threads 2 The state of "+Thread.currentThread().getState());
System.out.println(" Threads 2 end of execution !");
// Only called ThreadDemo09 Class object notify() After the method , This thread will enter the object lock pool , Ready to acquire object lock , Enter the running state .
// If you don't call notify() or notifyAll() Method , The thread is always suspended .
ThreadDemo09.class.notify();
//ThreadDemo09.class.notifyAll();
System.out.println(" After waking up Threads 1 state "+threadA.getState());
}
},"B");
threadB.start();
}
}2.3 Execution results

From the above execution results, we can see ,B End of thread call notify() After the method , It doesn't immediately hand over control of the thread .A After the thread is awakened , It doesn't immediately change the state to RUNNABLE. But first become BLOCKED state , Then compete for locks , After successfully competing to regain the lock , Will change the status to RUNNABLE, And then we can execute .
This is because in the Java in , Each object has a corresponding Monitor lock ,Monitor The lock maintains a EntryList and WaitSet aggregate . When a thread is blocked , Will be put into EntryList Collection , The corresponding state is BLOCKED state . When a thread calls wait() After the method , Will be added to WaitSet Collection , The corresponding state is WAITING、TIMED_WAITING state . Above we also analyzed , Threads “ Awakened ” and “ Gets the lock ” It's two processes , The awakened thread needs to re participate in lock contention , So the thread starts from WaitSet After waking up , Was added to EntryList In line ( Because the state changes to BLOCKED).
3. Method features ( a key )
- wait() yes Object The method in , because Java It is hoped that each can be controlled concurrently Object object ;
- Only the thread that has acquired the lock , To call the lock object wait() Method , Otherwise it will throw IllegalMonitorStateException abnormal ;
- call wait() After the method , Its thread will give up the object lock , Enter the object waiting pool , Threads in the waiting pool do not compete for synchronization locks ;
- call wait() Method to call notify() After the method , The thread in which it is located will enter the lock flag waiting pool , Ready to acquire object lock , Enter the operable state , Otherwise, it will be suspended all the time ;
- After the thread is awakened , Does not immediately change the state to RUNNABLE, But first become BLOCKED state , You can only continue to execute after participating in the lock competition .
6、 ... and . sleep()、yield()、join()、wait() The difference between ( a key )
1. sleep() Method
- sleep() The method is Thread Static method of , When calling, you need to specify the waiting time ;
- sleep() Methods do not depend on synchronized synchronizer , Can be used independently ;
- sleep() Method allows the currently executing thread to pause execution for a specified time , Enter blocking state ;
- sleep() Method can let other threads with the same or high priority get the chance to execute , You can also give low priority threads execution opportunities ;
- sleep() Method will not release “ Lock sign ”, That is to say, if there is synchronized Synchronized block , Other threads cannot access shared data ;
- sleep() No need to wake up ;
- sleep() Generally used for the sleep of the current thread , Or polling pause operation ;
- sleep() Will give up CPU Resources and force context switching .
2. yield() Method
- yield() Method is also Thread Static method of , But this method has no time parameter ;
- yield() Method will return the current thread to the executable state , perform yield() The thread of the method may be scheduled after the next time , It will also let the thread obtain the execution right to continue execution ;
- yield() Method can only make the same priority or high priority thread get execution opportunity ;
- yield() Method will not release “ Lock sign ”.
3. join() Method
- join() The method is Thread Instance method of ;
- When a new thread is added , Will put the main thread in wait for (WAITING) state , Wait until the other threads are no longer active .
4. wait() Method
- wait() The method is Object The instance method of the object ;
- wait() Methods need to be associated with notify() or notifyAll() The two methods work together ;
- wait() Method must be in synchronized Use... In statement blocks , That is to call wait() Method must have an object lock ;
- wait() Method will release the object's “ Lock sign ”, Causes the current thread to pause execution , And put the current thread into Object waiting pool in . Until I call notify() After the method , Any thread will be removed from the object waiting pool and put into Lock flag waiting pool ( Lock pool for short ) in , Only the threads in the lock flag waiting pool can acquire the ownership of the synchronization lock ;
- wait() Methods need to be awakened ;
- wait() It is mostly used for communication between multiple threads ;
- wait() Not necessarily give up CPU execution time ,wait There may be a chance to re compete until the lock continues to execute ;
7、 ... and . Conclusion
thus , Yige Let's finish explaining the differences between these methods , Now do you remember ? If you still want to know ” Aoi Sora “ and ” Teacher Wu “ The difference between , Please leave a message in the comment area 666, Yige Just send you a link ○( ^ Dish ^)っHiahiahia…
边栏推荐
- 原生JS怎么生成九宫格
- Sitelock nine FAQs
- Select sort
- CMake教程系列-01-最小配置示例
- Jupyter notebook displays a collection of K-line graphs
- Time complexity analysis
- Raki's notes on reading paper: discontinuous named entity recognition as maximum clique discovery
- 迅为恩智浦iTOP-IMX6开发平台
- 走进江苏作家诗人胭脂茉莉|世界读书日
- A quick look at the statistical data of 23 major cyber crimes from 2021 to 2022
猜你喜欢

AutoJS代碼能加密嗎?YES,AutoJS加密技巧展示

怎么使用Vant实现数据分页和下拉加载

代码签名、驱动签名的常见问题解答

公司电脑强制休眠的3种解决方案

How vscode debugs into standard library files / third-party package source code

oracle怎么设置密码复杂度及超时退出的功能
![[dry goods sharing] the latest WHQL logo certification application process](/img/c3/37277572c70b0af944e594f0965a6c.png)
[dry goods sharing] the latest WHQL logo certification application process

如何在 JupyterLab 中把 ipykernel 切换到不同的 conda 虚拟环境?

Shenzhen CPDA Data Analyst Certification in July 2022

NPDP产品经理国际认证考试报名有什么要求?
随机推荐
Multi card server usage
Redis+AOP怎么自定义注解实现限流
AutoJS代碼能加密嗎?YES,AutoJS加密技巧展示
What should academic presentation /ppt do?
2. < tag dynamic programming and 0-1 knapsack problem > lt.416 Split equal sum subset + lt.1049 Weight of the last stone II
CMake教程系列-04-编译相关函数
Network neuroscience -- a review of network Neuroscience
[Postgres] Postgres database migration
什么是证书透明度CT?如何查询CT logs证书日志?
What are the requirements for NPDP product manager international certification examination?
Pytoch learning (II)
[dry goods sharing] the latest WHQL logo certification application process
Merge sort
SSL证书格式转化的两种方法
Global and Chinese market for defense network security 2022-2028: Research Report on technology, participants, trends, market size and share
Three solutions to forced hibernation of corporate computers
C console format code
Seven common errors of SSL certificate and their solutions
What is certificate transparency CT? How to query CT logs certificate logs?
Raki's notes on reading paper: discontinuous named entity recognition as maximum clique discovery