Differences between wait and sleep in Java

Source: Internet
Author: User


Multithreading in Java is a preemptible mechanism rather than a time-sharing mechanism. A thread can run, run, block, or die in the following states. A preemptible mechanism means that multiple threads are running, but only one thread is running. When multiple threads access Shared data, the thread needs to be synchronized. Comparison of several main methods in the thread: Methods of the thread class: Sleep (), yield () and other object Methods: Wait () and Policy () each object has a machine lock to control synchronous access. The synchronized keyword can interact with the machine lock of the object to synchronize threads. Because the sleep () method is a thread class method, it cannot change the machine lock of the object. So when sleep () is called in a synchronized method, although the thread is sleeping, the machine lock of the object is not released, and other threads still cannot access this object. The wait () method releases the machine lock while the thread is sleeping. Other threads can access this object. The yield () method is to stop the current thread and run threads with the same priority. If there is no thread with the same priority, the yield () method will not work. The end mark of a thread is: the end of the run () method. The mark of a lock being released is that the synchronized block or method ends. Wait () and notify () Methods: When a thread executes the wait () method, it enters a waiting pool related to the object, the machine lock of the object is also lost. When it is awakened by a notify () method, the threads in the wait pool will be placed in the lock pool. This thread acquires the machine lock from the lock pool and then returns to the interrupt site before wait. The join () method stops the current thread and waits until another thread that calls the join method terminates. It is worth noting that the thread does not necessarily run immediately after being activated, but enters the queue of the runable thread.


In common: they are all in a multi-threaded environment. They can block a specified number of milliseconds in a program call and return results.

Difference: thread. Sleep (long) can not be called under the synchronized block, and the use of thread. Sleep () will not lose the current thread's synchronization lock on any object (MONITOR );
Object. Wait (long) must be used in the synchronized block. After being called, the monitor of the object is lost. The advantage of this is that it does not affect other threads to operate the object.

Here is an example of Java. util. Timer.

Private void mainloop (){
While (true ){
....
Synchronized (Queue ){
.....
If (! Taskfired) // task hasn' t yet fired; wait
Queue. Wait (executiontime-currenttime );
}
}

The reason why queue. Wait () is used instead of thread. Sleep () is that the queue object lock is temporarily abandoned and other threads can be allowed to perform some synchronization operations. For example:
Private void sched (timertask task, long time, long period ){
Synchronized (Queue ){
...
Queue. Add (task );
}
}

However, as mentioned in the previous article, queue is used. the prerequisite for wait (long) is that the execution time of the sched () action is short. Otherwise, if it is long, the queue. wait () cannot wake up on time.

(2)

As mentioned above, the wait/notify mechanism and thread also has a static sleep () method, which can also suspend the thread for a period of time. The difference between sleep and wait is that sleep does not release the lock, and the pause of sleep is different from that of wait. OBJ. Wait will make the thread enter the waiting set of the OBJ object and wait for awakening.

However, both wait () and sleep () can interrupt the pause state of the thread through the interrupt () method, so that the thread immediately throws interruptedexception.

If thread a wants to terminate thread B immediately, it can call the interrupt method for the thread instance corresponding to thread B. If thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception and directly return in catch () {} to end the thread safely.

It should be noted that interruptedexception is thrown by the thread itself from the internal, not by the interrupt () method. When interrupt () is called for a thread, if the thread is executing common code, the thread will not throw interruptedexception. However, once the thread enters wait ()/sleep ()/join (), interruptedexception is immediately thrown.


(3)

The following is a post I saw on the csdn forum, which involves the understanding of synchronization, wait (), notify (), and other concepts, I tried to analyze the wait () and Policy () methods based on some original replies and related concepts in think in Java. Thank you for your advice.

The problem is as follows:

File: // analyze this program and explain it. here we will focus on synchronized, wait (), notify. Thank you!
Class threada
{
Public static void main (string [] ARGs)
{
Threadb B = new threadb ();
B. Start ();
System. Out. println ("B is start ....");
Synchronized (B) // What does B in parentheses mean and what does it do?
{
Try
{
System. Out. println ("waiting for B to complete ...");
B. Wait (); // What does this sentence mean?
System. Out. println ("completed. Now back to main thread ");
} Catch (interruptedexception e ){}
}
System. Out. println ("total is:" + B. Total );
}
}


Class threadb extends thread
{
Int total;
Public void run ()
{
Synchronized (this)
{
System. Out. println ("threadb is running ..");
For (INT I = 0; I <100; I ++)
{
Total + = I;
System. Out. println ("total is" + total );
}
Notify ();
}
}
}

To analyze this program, we must first understand y () and wait (). Why didn't we record these two methods when recording the thread a few days ago, because these two methods are not in the Thread class, it belongs to the underlying object base class. That is to say, not only is thread, but every object has the functions of notify and wait. Why? Because they are used to manipulate the lock, and each object has a lock, the lock is the basis of each object. Since the lock is the basis, the method of manipulating the lock is of course the most basic.

Let's take a look at it. First, we 'd better review Part 1 of think in Java 14.3.1: waiting and notification, that is, wait () and policy.

According to think in Java, "Wait () allows us to put threads into the" Sleep "state, while actively waiting for conditions to change. in addition, the thread will be awakened only when one notify () or notifyall () Change and check whether the conditions have changed."

Let's explain this sentence.
"Wait () allows us to put the thread into the" Sleep "State. That is to say, wait also blocks the current thread, which is the same as sleep or suspend. what is the difference between it and sleep and suspend?

The difference is that "(wait) and" actively "wait for conditions to change", this is critical, and sleep and suspend cannot do it. because we sometimes need the help of synchronized to prevent conflicts between threads. Once synchronization is used, the object is locked, that is, the object lock is obtained, other threads that want to use the object lock can only wait in the queue and wait until the synchronization method or all the programs in the synchronization block have run. in the synchronization method and synchronization block, neither sleep () nor suspend () can be unlocked when they are called by themselves. They all occupy the used object lock.
However, wait does. It allows the synchronization method or synchronization block to temporarily discard the object lock and temporarily give it to other persons who need the object lock (Here it should be a program block or thread) for use, this means that other Synchronization Methods in the thread object can be called during wait () execution! In other cases (sleep, suspend), this is impossible.
But pay attention to what I mentioned above. I just temporarily give up the object lock and use it for other threads. The thread where my wait is located still needs to reclaim this object lock. What is wait? It's wait. I can get it back when someone else finishes using it!
Well, how can we take back the object lock?
The first method is to limit the lending time. set the parameter in wait (), for example, wait (1000). in milliseconds, it indicates that I only lent out for 1 second. After one second, I automatically took it back.
The second method is to let the borrower inform me that he has used up his work and will return it to me. at this time, I will immediately withdraw it. ah, what if I took it back one hour later and it took only half an hour for someone else to finish it? Depend! Of course, it will be recovered after it is used up. It also determines how long it will take.

So how can someone tell me? I believe everyone can think of it, notify (), this is the last sentence "and only when a notify () or notifyall () changes, the thread will be awakened.
Therefore, we can place a wait () and Policy () in any synchronous method or within the synchronization block, regardless of whether the class is prepared for thread-related processing. In fact, we can only call wait () and Policy () in the synchronous method or block ().

At this time, it is easy to explain the above program.

Synchronized (B) {...}; defines a synchronization block and uses B as the resource lock. B. wait (); Means to temporarily release the lock and block the current thread, so that other threads that use the same lock have the opportunity to execute it. Here, the thread B must use the same lock. after this thread is executed to a certain point, it notifies the wait thread by running y (). The lock is used up. After the synchronization block in which notify () is running, the thread where wait is located can continue the execution.










Wait

Causes the current thread to wait until other threads call this objectnotifyMethod ornotifyAllMethod.

The current thread must own this object monitor. This thread releases ownership of this monitor and waits until other threads pass the callnotifyMethod, ornotifyAllMethod to notify the waiting thread to wake up on the monitor of this object. Then the thread will not continue execution until it obtains ownership of the monitor again.

Sleep

Sleep the currently running thread (paused) within a specified millisecond ). This thread does not lose the ownership of any monitor.

Wait and sleep...

Wait is a method of the object class, and its range is the thread that stores the object instance.

Sleep () is a static method exclusive to the Thread class, targeting a specific thread.

Generally, you do not need to use wait if you just want to pause the thread. sleep (...) this method is similar to sleeping when the sleep thread does not necessarily resume execution immediately after the end of the time.

// Thread
Try {
System. Out. println ("A will sleep ");
This. Sleep ();
} Catch (interruptedexception e ){
// A has been interrupted
System. Out. println ("A was interrupted ");
}

// Other threads
A. Interrupt ();

If the wait method needs to be used for mutual exclusion through lock, otherwise the java. Lang. illegalmonitorstateexception will be thrown.

Private object lock = new object ();
...
Synchronized (getlock ())...{
Getlock (). Wait (timeout );
}
...
Protected object getlock ()...{
Return lock;
}
...
Public void broadcast (){
Synchronized (getlock ()){
Getlock (). policyall ();
}
}

The preceding implementation uses the wait method in a thread, and a fine-grain lock is used to control the thread mutex.

The wait method suspends the execution of the thread in which the object is located, so that the object enters the waiting state until the waiting time of the notify method notification or wait is reached. The sleep method suspends the running of the thread, so that the thread enters the sleep state until the interrupt method is used to interrupt its sleep or sleep.

When the wait method enters the waiting state, the synchronization lock is released (the lock object in the above example), while the sleep method does not release the synchronization lock. Therefore, when no one goes to interrupt when a thread sleep infinitely, the program will be in great trouble.

Intimacy... And policy... And interrupt...

Wait and policy...

Notify is used to notify the thread, but the thread needs to get the lock before notify. It must be written in synchronized (lockobj. Wait also looks like this. A thread needs to release a lock and can only release it when it gets the lock. Therefore, wait also needs to be placed in synchronized (lockobj. See the following example:

// In thread
Synchronized (lockobject ){
While (! Condition ){
Lockobject. Wait ();
}
// Todo the running part
}
  
// In thread B
Synchronized (lockobject ){
Condition = true;
Lockobject. Policy ();
}

When thread A obtains the lock, it constantly determines the condition. When it does not meet the lock condition, it releases the lock and enters the waiting state. B gets the lock, changes the condition, notifies a, then B leaves the lock area, and a gets the part where the lock executes the run.

Sleep and sleep y...

I don't think it makes sense for them to get together, because the thread does not release the lock that he occupies during sleep, so notify cannot wake him up.

Sleep and interrupt...

Interrupt is a very violent method. when you interrupt the sleep of a thread, you do not need to get the lock of the thread. Although violent, it is also useful. When a thread has no time limit to sleep, only interrupt can wake him up. Interrupt will throw interruptedexception. This exception is automatically thrown by the Thread class. Therefore, interrupt has a strong blocking effect.

Wait and interrupt...

Interrupt can interrupt wait. Unlike sleep interruption, the interrupted wait thread will not throw interruptedexception until it gets the lock again.

Forgotten... Resume and suspend...

Resume and suspend have been abandoned by Java because they are inherently causing thread deadlocks.

Suspend is a greedy guy. When a thread is in suspend, the thread stops, but still holds the lock obtained before that. Other threads cannot use any resources they lock, unless the suspended thread is resume before it continues to run. For thread synchronization, it is much safer to use wait and policy.

 

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.