Java--Sleep and wait

Source: Internet
Author: User

1. The source of the two

  Sleep (), which is the static method/static local method under Thread.

Wait (), which is the final method of object ().

 2. Source Code Analysis

A, sleep ()

1   Public Static voidSleepLongMillis,intNanos)2     throwsinterruptedexception {3         if(Millis < 0) {4             Throw NewIllegalArgumentException ("Timeout value is negative");5         }6 7         if(Nanos < 0 | | Nanos > 999999) {8             Throw NewIllegalArgumentException (9"Nanosecond timeout value out of range");Ten         }
A if(Nanos >= 500000|| (Nanos! = 0 && Millis = = 0)) { -millis++; - } the - sleep (Millis); -}

When you call Sleep (Millis,nanos), the internal call to sleep (Mills) is as follows:

 Public Static void sleep (long Millis) throws interruptedexception;

This is a static local method

It is important to have one sentence:: The thread does not lose ownership of any monitors.  The thread that calls the method does not lose any monitoring. All locks originally owned by the thread are not lost.

  Instance:

An entity class user

1  Public classUser {2     Private intAge ;3 4      Public intGetage () {5         returnAge ;6     }7 8 @Override9      PublicString toString () {Ten         return"User [age=" + Age + "]"; One     } A  -      Public voidSetage (intAge ) { -          This. Age =Age ; the     } -  -}

Operations on this entity class

1  Public classMain {2 3      Public Static voidMain (string[] args) {4 5         FinalUser User =NewUser ();6User.setage (10);7 8         synchronized(user) {9             Try {TenSystem.out.println ("Current thread <---->" One+ Thread.CurrentThread (). GetName () + "<-----> Ready to Hibernate"); A  -Thread.Sleep (10000);//Current thread hibernation -  theSystem.out.println ("Current thread <---->" -+ Thread.CurrentThread (). GetName () + "<-----> Complete Hibernation"); -  -                 //creates a new thread that performs a related operation on the current lock object +                 NewThread ("New Thread") { -                      Public voidrun () { +System.out.println ("Current Thread--->" A+Thread.CurrentThread (). GetName ()); at System.out.println (User.getage ()); -                     }; - }.start (); -  -}Catch(interruptedexception e) { -                 //TODO auto-generated Catch block in e.printstacktrace (); -             } to         } +     } -}

Execution Result:

Current thread  <---->main<-----> Prepare to hibernate current thread  <---->main<----->  Complete Hibernate current thread  ---> New Thread10

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. Therefore, the thread will release the corresponding lock only at the end of the synchronized block.

b, Wait ()

The thread releases ownership of this monitor
Until another thread notifies threads waiting on this object ' s monitor-to-wake up

The thread that invokes the method must have control over the object. After the call, the control is released until it wakes up by another thread (notify () | Notifyall ()).

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

After that, the awakened thread continues to wait until the object's control is retrieved.

1    Public Final void throws interruptedexception {2         Wait (0); 3     }

Call the Wait (0) method--final native

   Public Final native void Wait (longthrows interruptedexception;

The specified amount of real time has elapsed, more orless. If timeout is zero, however, then real time was not taken into consideration and the thread simply waits until notified. Then removed from the wait set for this object and re-enabled for thread scheduling. The wait time is reached or awakened (there is also a wake-up method--spurious wakeup, which can be viewed in detail), removed from the wait set of the thread, waiting to be dispatched again.

    

Welcome to shoot Bricks

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