The difference between sleep and wait

Source: Internet
Author: User

Sleep refers to when the thread is called, the CPU does not work, the image is described as "occupy the CPU Sleep", at this time, the system's CPU part of the resources are occupied, other threads can not enter, will increase the time limit.
Wait means that the thread is in the waiting state and is visually described as "waiting for CPU", at which point the thread does not occupy any resources and does not increase the time limit.
So
Sleep (100L) means: Consumes CPU, thread sleeps 100 milliseconds
Wait (100L) means: CPU not occupied, thread waits 100 milliseconds

The difference between sleep and wait

1. The two methods come from different classes , namely thread and object
2, the most important is that the sleep method does not release the lock , and the wait method frees the lock, so that other threads can use the synchronization control block or method.
3, Wait,notify and Notifyall can only be used in synchronous control method or synchronous control block, and sleep can be
Use Anywhere ( use range )
Synchronized (x) {
X.notify ()
or wait ()
}
4. Sleep must catch exceptions , while Wait,notify and notifyall do not need to catch exceptions

The difference between sleep () and wait ()

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. This article mainly describes the difference between sleep () and wait (), as seen together.

AD:

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. A comparison of several main methods in a thread:

Methods of the Thread class:sleep (), yield (), etc.

Method of object: Wait() and notify (), etc.

Each object has a machine lock to control synchronization access. The Synchronized keyword can interact with the object's machine lock to achieve thread synchronization.

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 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. The yield () method will not work if there are no equal priority threads.

The 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.

    1. Private void Mainloop () {
    2. while (true) {
    3. ....
    4. Synchronized (queue) {
    5. .....
    6. if (!taskfired) //Task hasn ' t yet fired; wait
    7. Queue.wait (Executiontime-currenttime);
    8. }
    9. }

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:

    1. Private void Sched (timertask task, long time, long period) {
    2. Synchronized (queue) {
    3. ...
    4. Queue.add (Task);
    5. }
    6. }

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.

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.

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:

file://analysis of this procedure, and explain, focus on synchronized, wait (), notify Thank you!

  1. Class Threada
  2. {
  3. Public static void Main (string[] args)
  4. {
  5. THREADB b=New threadb ();
  6. B.start ();
  7. System.out.println ("B is start ....");
  8. Synchronized (b)//What does B mean in parentheses and what is the role?
  9. {
  10. Try
  11. {
  12. System.out.println ("Waiting for B to complete ...");
  13. B.wait ();  //What does this sentence mean, who is it to wait?
  14. System.out.println ("Completed.now back to Main thread");
  15. }catch (Interruptedexception e) {}
  16. }
  17. System.out.println ("Total is:" +b.total);
  18. }
  19. }
  20. Class threadb extends Thread
  21. {
  22. int total;
  23. Public Void Run ()
  24. {
  25. Synchronized (this)
  26. {
  27. System.out.println ("THREADB is running..");
  28. for (int i=0;i<100;i++)
  29. {
  30. Total +=i;
  31. System.out.println ("Total is" +total);
  32. }
  33. Notify ();
  34. }
  35. }
  36. }

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 blocked by the current thread, which is the same as sleep or suspend. That and

What is 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.

    1. Synchronized (b) {...} ;

Defines a synchronization block, using 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 sleep and wait

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.