Usage and distinction of sleep (), wait () and notify () and Notifyall (), Suspend and resume (), yield (), join (), interrupt () in Java threads __java

Source: Internet
Author: User
Tags thread class
It programmer development must-all kinds of resources download list, the most complete IT resources in history, personal collection summary.

From the operating system point of view, the OS maintains a ready queue (the Ready thread queues). And at some point the CPU only serves the thread at the head of the queue in the ready queue.
But the thread that is currently being serviced may feel that the quality of the CPU service is not good enough, so quit early, this is yield.
Or the thread that is currently being serviced needs to sleep for a while and then wake up and continue to be serviced.
The sleep method is not recommended and can be used with wait.
The thread exits best to implement itself, in the running state has been checking a state, if this state is true, it has been running, if the outside world changed this state variable, then the thread will stop running.
Sleep () causes the current thread to stagnate, so the thread performing the sleep () is definitely not executing for the specified time; yield () simply causes the current thread to return to the executable state, so the thread that executes the yield () may be executed immediately after it enters the executable state.
Sleep () allows lower-priority threads to be executed, and, of course, can give the same priority and High-priority threads an opportunity to execute; yield () can only give the same priority thread the chance to execute.
When you call Wait (), the thread frees up its "lock flag" so that other synchronized data in the object where the thread is located can be used by another thread.
Waite () and notify () must be invoked in the synchronized function or synchronized block because they operate on the lock flags of the objects. If invoked in the Non-synchronized function or in the non-synchronized block, the illegalmonitorstateexception exception will occur at run time, although it can be compiled.

the state of the thread
A thread has four states, and any thread must be in one of these four states:
1) (NEW): The thread object has been generated, but has not yet been started, so it cannot be executed. Before the start () function is generated for a thread object by new.
2 executable (Runnable): Each system that supports multithreading has a scheduler, and the scheduler selects a thread from the thread pool and starts it. When a thread is in an executable state, it may be in the thread pool waiting for the scheduler to start it, or it may already be executing. If a thread object's start () method is executed, the thread is in an executable state, but it is obvious that the thread is not necessarily executing at this time.
3 Death (Dead): When a thread ends normally, it is in a dead state. If a thread's run () function finishes executing, the thread enters the dead state.
4 Stagnation (Blocked): When a thread is in a stagnant state, the system scheduler ignores it and does not schedule it. When a stalled thread returns to its executable state, it is likely to be executed again. If you call the Wait () function on a thread, the thread enters a standstill state, which can be returned to the executable state only two times after you call notify or Notifyall on the thread two times.

Usage
Sleep ()

Lets the currently executing thread hibernate (suspend execution) within the specified number of milliseconds, which is affected by the system timer and scheduler precision and accuracy.

Because the sleep () method is a method of the thread class, it cannot alter the object's machine lock. So when you call sleep () in a synchronized method, the thread is dormant, but the object's machine lock is not freed, and the object is still inaccessible to other threads. The sleep () method does not need to be executed in a synchronized block of code. But sleep () can interrupt the paused state of the thread through the interrupt () method, causing the thread to throw interruptedexception immediately.

Wait () and notify () and Notifyall ()
Wait ()
Method releases the drop 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 to the wait () method, it enters a waiting pool associated with the object, loses the machine lock of the object, and allows other threads to perform some synchronization operations. However, wait () can interrupt the paused state of the thread through the interrupt () method, causing the thread to throw interruptedexception immediately.

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

Okay, so how do we get the object locked back?

The first method, which limits the time to lend. Setting parameters in Wait (), such as Waiting (1000), in milliseconds, indicates that I only borrow out of 1 seconds, and after a second, I automatically retract.

The second way, let the people who borrowed to inform me, he used up, to give me back. At this moment, I will take it back. Hey, if I set up 1 hours later, the others only spent half an hour to finish, then how to do? Damn it! Of course, used up to take back, but also how long I set the time ah.

So how do people inform me? I believe we all can think of, notify (), this is the last sentence "and only when a notify () or notifyall () change, the thread will be awakened" meaning.

Notify ()Wakes up a single thread waiting on this object monitor. When it is awakened by a notify () method, the thread in the wait pool is placed in the lock pool. The thread waits to get the machine lock from the lock pool and then back to the interrupt scene before Wait ().

Notifyall ()Wakes up all 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 noteworthy that the thread does not run immediately after being activated, but instead goes into the queue of the running thread. However, join () can interrupt the paused state of the thread 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 is no equal priority thread.

Interrupt ()
Thread in interrupt (). It should be noted that the interruptedexception is thrown by the thread itself, not by the interrupt () method. When interrupt () is invoked on a thread, the thread does not throw interruptedexception if it is executing normal code. However, once the thread has entered the wait ()/sleep ()/join (), the interruptedexception is thrown immediately.


the difference between each method
Thread Method Name Whether to release the sync lock Whether you need to call in a synchronized block of code Whether the method has been discarded Whether it can be interrupted
Sleep () Whether Whether Whether Is
Wait () Is Is Whether Is
Suspend Is
Resume () Is
Join () Whether Is


Related Article

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.