The difference between the wait method and the Sleep method

Source: Internet
Author: User

I. Concepts, principles, distinctions

Multithreading in Java is a preemptive mechanism rather than a time-sharing mechanism. Threads have the following states: Can run, run, block, die.       The preemption mechanism refers to having multiple threads in a running state, but only one thread is running. When there are multiple threads accessing the shared data, the threads need to be synchronized. Comparison of several main methods in a thread: Methods for the Thread class: sleep (), yield (), and so on object: Wait () and notify (), etc. Each object has a machine lock to control synchronous access。 The Synchronized keyword can interact with the object's machine lock to achieve thread synchronization. because the sleep () method is thread class, so it cannot change the machine lock of the object。 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 wait () method frees the machine lock while the thread sleeps, and other threads can access the object. The Yield () method is to stop the current thread and let the same priority thread run. If there are no equal priority threads, then yield () method will not workthe flag at the end of a thread is: the Run () method ends. the flag that a machine lock is released is: Synchronized block or method end. The wait () method and the Notify () method: When a thread executes to the wait () method, it enters into a waiting pool associated with the object and loses the machine lock on the object. When it is awakened by a notify () method, the threads in the waiting pool are placed in the lock pool. The thread obtains the machine lock from the lock pool and then goes back to the interrupted scene before Wait (). 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 enters the queue of the running thread.

Common denominator: They are all in multi-threaded environment, can block a specified number of milliseconds at the call of the program, and return.

Different points: thread.sleep (long) can not be reduced by synchronized block, and using Thread.Sleep () will not lose the current thread to any object of the synchronization lock (monitor);
Object.wait (long) must be used in the synchronized block, and after the call loses the monitor for object, the benefit is that it does not affect other threads manipulating the object.

Give a java.util.Timer example to illustrate.

private void Mainloop () {
while (true) {
....
Synchronized (queue) {
.....
if (!taskfired)//Task hasn ' t yet fired; Wait
Queue.wait (Executiontime-currenttime);
}
}

The reason why you should use Queue.wait () instead of Thread.Sleep () is because you temporarily discard the object lock on the queue, allowing other threads to perform some synchronous operations. Such as:
private void Sched (TimerTask task, long time, long period) {
Synchronized (queue) {
...
Queue.add (Task);
}
}

But as mentioned in the previous article, the precondition for using queue.wait (long) is that the sched () action executes for a short time, otherwise if it is long, then queue.wait () will not be able to wake up on time.

two. Thread's interrupt method and Sleep,wait

In front of the wait/notify mechanism, thread also has a sleep () static method, which also allows the thread to pause for a while. The difference between sleep and wait is that sleep does not release the lock, and sleep pauses and wait pauses are not the same. Obj.wait causes the thread to enter the waiting set of the Obj object and waits for a wake-up.

But wait () and sleep () can break the thread's suspend state through the interrupt () method, causing the thread to throw interruptedexception immediately.

If thread A wants to end thread B immediately, you can call the interrupt method on the thread instance that corresponds to threads B. If thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception, and return directly in catch () {} to safely end the 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.

three. Reprint CSDN on the sleep,wait of a piece of code, and analyze the understanding under

Here is a post I originally saw on the CSDN forum, involving synchronization, wait (), notify () and other concepts of understanding, I try to according to some of the original replies and think in Java related concepts will Wait () and notify () these two methods to dissect a bit, Welcome advice.

The problem is as follows:

Analyze This procedure, and explain, focus on synchronized, wait (), notify Thank you!
Class Threada
{
public static void Main (string[] args)
{
    threadb b=new threadb (); br>    B.start ();
    System.out.println ("B is start ....");
    synchronized (b)//What does the 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, who is it to wait?
        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, first understand the Notify () and wait (), why did not record the thread in the previous days when the two methods are not recorded, because these two methods are not belong to the thread class, but belong to the bottom of the object base class, that is, not only thread, Each object has notify and wait functions, why? Because they are used to manipulate locks, and each object has a lock, the lock is the basis of each object, since the lock is the basis, then the method of locking is the most basic.

Before looking down, it is best to review the Think in Java 14.3.1 Part 3: Wait and notice, that is, wait () and notify.

According to think in Java, "Wait () allows us to put the thread into the" sleep "state while" actively "waiting for the condition to change. And only when a notify () or Notifyall () changes, the thread is awakened and the condition is checked for change ."

Let's explain the sentence.
Wait () allows us to place the thread in the sleep state, which means that wait is also blocking the current thread, which is the same as sleep or suspend. What's the difference between sleep,suspend?

The difference is that "(wait) while" actively "waiting for the condition to change" is critical, and sleep and suspend cannot do it. Because we sometimes need to use synchronization (synchronized) Help to prevent conflicts between threads, and once using synchronization, the object will be locked, That is, to get the object lock, the other threads to use the object lock can only be queued, wait until the synchronization method or the synchronization block of the program all run the opportunity. In the synchronization method and the synchronization block, whether sleep () or suspend () is not possible to unlock itself when called, They're all hogging the lock on the object being used.
Wait can, however, allow the synchronous method or the synchronization block to temporarily discard the object lock, and temporarily give it to someone else who needs an object lock (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, it's 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.
Therefore, we can place a wait () and notify () inside any synchronous method or synchronization block, regardless of whether the class is ready for processing involving threading. And in fact, we can only call Wait () and notify () in the synchronization method or the synchronization block.

It's a breeze to explain the procedure above.

Synchronized (b) {...} Define a synchronization block and use 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, and the same lock is used here as the B thread itself. This thread will notify the wait thread with notify () after executing to a certain place, the lock has been exhausted and is notify ( After the synchronization block is running, the wait thread can continue executing.

The difference between the wait method and the Sleep method

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.