The usage and difference of sleep(), wait() and notify() and notifyAll(), suspend and resume(), yield(), join(), interrupt() in Java threads

Well written, reproduced here for your reference;

Reprinted from the original address: http://zheng12tian.iteye.com/blog/1233638

From the perspective of the operating system, os will maintain a ready queue (ready thread queue). And at a certain time, the cpu only serves the thread at the head of the queue in the ready queue. 
However, the thread currently being served may feel that the service quality of the CPU is not good enough, so it exits in advance, which is yield. 
Or the thread that is currently being serviced needs to sleep for a while and continues to be serviced after waking up, which is sleep. 
The sleep method is not recommended, you can use wait. 
It is best to implement thread exit by yourself. Always check a state in the running state. If this state is true, it will continue to run. If the outside world changes this state variable, the thread will stop running. 
sleep() makes the current thread enter a stagnant state, so the thread executing sleep() will definitely not execute within the specified time; yield() just makes the current thread return to the executable state, so the thread executing yield() may It is executed again immediately after entering the executable state. 
sleep() can give low priority threads a chance to execute, and of course threads of the same priority and high priority have a chance to execute; yield() can only give threads of the same priority a chance to execute. 
When wait() is called, the thread will release the "lock flag" it holds, so that other synchronized data in the object where the thread is located can be used by other threads. 
Because waite() and notify() operate on the object's "lock flag", they must be called in a synchronized function or synchronized block. If the call is made in a non-synchronized function or a non-synchronized block, although it can be compiled and passed, an IllegalMonitorStateException exception will occur at runtime. 

The state of the 
thread There are four states of the thread, any thread must be in one of these four states: 
1) Generated (New): The thread object has been generated, but it has not been started, so it cannot be executed. For example, after a thread object is generated by new, it is not called the start() function. 
2) Runnable: Every system that supports multithreading has a scheduler, which selects a thread from the thread pool and starts it. When a thread is in the executable state, it may be in the thread pool waiting for the scheduler to start it; it may be already executing. For example, after executing the start() method of a thread object, the thread is in an executable state, but it is obvious that the thread is not necessarily executing at this time. 
3) Dead: When a thread ends normally, it is in a dead state. For example, after a thread's run() function is executed, the thread enters the dead state. 
4) Blocked: When a thread is in a stalled state, the system scheduler ignores it and does not schedule it. When a stalled thread returns to the executable state, it may re-execute. For example, after calling the wait() function on a thread, the thread enters the stagnant state, and it can only return to the executable state twice after calling notify or notifyAll on the thread twice. 

Usage 
sleep() 
Sleeps (pauses execution) the currently executing thread for the specified number of milliseconds, this operation is affected by the precision and accuracy of the system timer and scheduler. 

Since the sleep() method is a method of the Thread class, it cannot change the machine lock of the object. So when sleep() is called in a Synchronized method, although the thread sleeps, the machine lock of the object is not released, and other threads still cannot access the object. The sleep() method does not need to be executed in a synchronized block of code. But sleep() can interrupt the suspended state of the thread through the interrupt() method, so that the thread immediately throws InterruptedException. 

wait() and notify() and notifyAll() 
The wait() method releases the machine lock while the thread sleeps, and other threads can access the object. wait() must be executed in a synchronized block of code. When a thread executes the wait() method, it enters a wait pool associated with the object and loses the object's machine lock, allowing other threads to perform some synchronization operations. But wait() can interrupt the suspended state of the thread through the interrupt() method, so that the thread immediately throws InterruptedException. 

wait can make the synchronization method or synchronization block temporarily give up the object lock, and temporarily give it to other people who need the object lock (here it should be a program block, or thread), which means that the thread object can be called during the execution of wait() Other synchronization methods in ! In other cases (sleep, suspend), this is impossible. But pay attention to what I said earlier, only temporarily give up the object lock and temporarily use it for other threads, the thread where I wait is still required This object lock is taken back. What is the wait? That is, the wait is used up and returned to me! 

Ok, so how do I get the object lock back? 

The first method is to limit the time of borrowing. Setting parameters in wait(), such as wait(1000), in milliseconds, means that I only borrow for 1 second. , after a second, I automatically retract. 

第二种方法,让借出去的人通知我,他用完了,要还给我了.这时,我马上就收回来.哎,假如我设了1小时之后收回,别人只用了半小时就完了,那怎么办呢?靠!当然用完了就收回了,还管我设的是多长时间啊. 

那么别人怎么通知我呢?相信大家都可以想到了,notify(),这就是最后一句话"而且只有在一个notify()或notifyAll()发生变化的时候,线程才会被唤醒"的意思了. 

notify()唤醒在此对象监视器上等待的单个线程。当它被一个notify()方法唤醒时,等待池中的线程就被放到了锁池中。该线程将等待从锁池中获得机锁,然后回到wait()前的中断现场。 

notifyAll()唤醒在此对象监视器上等待的所有线程。 


suspend和resume() 
join() 
join()方法使当前线程停下来等待,直至另一个调用join方法的线程终止。值得注意的是,线程的在被激活后不一定马上就运行,而是进入到可运行线程的队列中。但是join()可以通过interrupt()方法打断线程的暂停状态,从而使线程立刻抛出InterruptedException。 

yield() 
Yield()方法是停止当前线程,让同等优先权的线程运行。如果没有同等优先权的线程,那么Yield()方法将不会起作用。 

interrupt() 
interrupt()中断线程。需要注意的是,InterruptedException是线程自己从内部抛出的,并不是interrupt()方法抛出的。对某一线程调用interrupt()时,如果该线程正在执行普通的代码,那么该线程根本就不会抛出InterruptedException。但是,一旦该线程进入到wait()/sleep()/join()后,就会立刻抛出InterruptedException。 


各个方法之间的区别

 

线程方法名称 是否释放同步锁 是否需要在同步的代码块中调用 方法是否已废弃 是否可以被中断
sleep()
wait()
suspend      
resume()      
join()    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899152&siteId=291194637