Usage and differences of methods such as sleep (), wait (), and notify () and notifyall (), yield (), join () in Java threads

Source: Internet
Author: User

usage and differences between sleep (), wait (), and notify () and Notifyall (), Suspend and resume (), yield (), join (), interrupt () in Java threads

from the operating system's point of view, the OS maintains a ready queue (the queued thread of readiness). And at some point the CPU only serves the thread that is in the queue header in the ready queue.
However, the thread that is currently being serviced may feel that the quality of the CPU service is not good enough, so quit early, which is yield.
or the thread that is currently being serviced needs to sleep for a while, wakes up and continues to be served, which is sleep.
The Sleep method is not recommended and can be used for wait.
a thread exit is best implemented by itself, always checking a state in the running state, if the state is true, running all the time, and if the state variable is changed by the outside world, then the thread stops running.
sleep () causes the current thread to stall, so the thread that executes sleep () is definitely not executed for the specified time, and yield () simply returns the current thread back to the executable state, so the thread executing yield () is likely to be executed immediately after entering the executable state.
sleep () allows a thread with a lower priority to be executed, and of course allows a thread with the same priority and high priority to execute, and yield () can only cause the thread with the same priority to have an opportunity to execute.
when Wait () is called, the thread releases the "lock flag" that it occupies, making other synchronized data in the object that the thread resides in can be used by other threads.
Waite () and notify () because they operate on the object's "lock flags," they must be called in the synchronized function or synchronized block. If the call is made in the non-synchronized function or non-synchronized block, the illegalmonitorstateexception exception will occur at run time, although it can be compiled.

the state of the thread
threads have four states, and any one thread must be in one of these four states:
1) Generation (NEW): The thread object has been generated but has not been started and cannot be executed. If a thread object is generated through new, it is not called before the start () function.
2) executable (Runnable): Each multithreaded system has a scheduler that selects a thread from the thread pool and starts it. When a thread is in an executable state, it indicates that it may be in the thread pool waiting for the scheduler to start it, or it may already be executing. If the start () method of a thread object is executed, the thread is in an executable state, but it is clear that the thread is not necessarily executing at this point.
3) Death (Dead): When a thread ends normally, it is in a dead state. A thread enters a dead state when the run () function of a thread finishes executing.
4) Stagnation (Blocked): When a thread is stuck, the system scheduler ignores it and does not schedule it. It is possible to re-execute a stalled thread when it is back in the executable state. If you call the Wait () function on a thread, the thread goes to a standstill, and it can return to the executable state two times after two calls to the thread notify or Notifyall.

usage
sleep ()
lets the currently executing thread hibernate (suspends execution) within the specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler.

because the sleep () method is a method of the thread class, it cannot alter the object's machine lock. So when sleep () is called in a synchronized method, the thread sleeps, but the object's machine lock is not released, and other threads still cannot access the object. The sleep () method does not need to be executed in a synchronized code block. However, sleep () can break the thread's pause state by Interrupt () method, causing the thread to throw interruptedexception immediately.

Wait () and notify () and Notifyall ()
The Wait () method frees the machine lock while the thread sleeps, and other threads can access the object. Wait () must be executed in a synchronized code block. When a thread executes to the wait () method, it enters into a waiting pool associated with the object and loses the object's machine lock, allowing other threads to perform some synchronization operations. But wait () can break the thread's pause state through the interrupt () method, causing the thread to throw interruptedexception immediately.

wait allows the synchronization method or the synchronization block to temporarily discard the object lock and temporarily give it to someone else who needs to lock the object (this should be a block, or thread), which means that the other synchronization methods in the thread object can be called during wait () execution! In other cases (sleep, Suspend, this is impossible. But notice what I said earlier, just temporarily give up the object lock, temporarily for other threads to use, I wait for the thread still to get this object lock back. Wait what?

Okay, so how do you lock the object back?

The first method is to limit the time borrowed. Setting parameters in Wait (), such as Wait (1000), in milliseconds, indicates that I only borrowed 1 seconds, and after a second, I automatically retracted.

The second way, let the person who borrowed to inform me, he used up, to give back to me. At that moment, I will take it back. Hey, if I set up 1 hours after the recovery, others only spent half an hour on the end, then what ?

So how do people tell me? I believe everyone can think of, notify (), this is the last word "and only when a notify () or notifyall () change, the thread will be awakened" means.

notify () wakes up a single thread waiting on this object monitor. When it is awakened by a notify () method, the threads in the waiting pool are placed in the lock pool. The thread waits for a machine lock from the lock pool and then returns to the interrupted scene before Wait ().

Notifyall () wakes up all the threads waiting on this object monitor.


suspend and resume ()
Join ()
The join () method causes the current thread to stop waiting until another thread that calls the Join method terminates. It is important to note that the thread is not necessarily running immediately after it is activated, but instead goes into the queue of the running thread. But join () can break the thread's pause state through the interrupt () method, causing the thread to throw interruptedexception immediately.

yield ()
The Yield () method is to stop the current thread and let the same priority thread run. The yield () method will not work if there are no equal priority threads.

Interrupt ()
interrupt () break thread. It is important to note that Interruptedexception is thrown from within the thread itself, not by the interrupt () method. When you call interrupt () on a thread, the thread does not throw interruptedexception at all if it is executing normal code. However, once the thread has entered wait ()/sleep ()/join (), the interruptedexception is immediately thrown.


the difference between the various methods

Thread Method Name Whether to release the sync lock Whether you need to call in a synchronized code block Whether the method is obsolete Whether it can be interrupted
Sleep () Whether Whether Whether Is
Wait () Is Is Whether Is
Suspend Is
Resume () Is
Join () Whether Is

Reprint site: http://zheng12tian.iteye.com/blog/1233638

Usage and differences of methods such as sleep (), wait (), and notify () and notifyall (), yield (), join () in Java threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.