Three, wait and wake up

Source: Internet
Author: User

In Object.java, interfaces such as Wait (), notify (), and notifyall () are defined.

Notify ()--wakes up a single thread waiting on this object monitor.
Notifyall ()--wakes up all the threads waiting on this object monitor.
Wait ()--keeps the current thread in a "waiting (blocking) state" until the other thread calls the Notify () method of this object or the Notifyall () method, and the current thread is awakened (enter " Ready state ").
Wait (long timeout)--keeps the current thread in a "waiting (blocking) state" until the other thread calls the Notify () method of this object or the Notifyall () method, or exceeds the specified amount of time ", the current thread is awakened (in "Ready state").
Wait (long timeout, int nanos)--keeps the current thread in a "waiting (blocking) state" until another thread calls the Notify () method of this object or the Notifyall () method, or some other thread interrupts the current thread. Or has exceeded an actual amount of time ", the current thread is awakened (into the ready state).

Note: 1.wait () and notify() must be used inside the synchronized block

2. The object calling wait () and notify () must be identical to the synchronized block lock object.

The role of Wait () is to allow the current thread to enter a wait state, and wait () will also let the current thread release the lock it holds. The role of Notify () and Notifyall () is to wake up the waiting thread on the current object, notify () is to wake up a single thread, and Notifyall () is to wake up all the threads.

 Public classWaittest { Public Static voidMain (string[] args) {FinalAtest a =Newatest (); Runnable Runnable=NewRunnable () {@Override Public voidrun () {a.m1 ();        }        }; /*** Test Call the Wait () method The current thread is in a wait state and releases the locks it holds. */Thread T1=NewThread (runnable); Thread T2=NewThread (runnable);        T1.start (); Try {            /*** The main thread can continue execution when the T1 threads have finished executing.             * If T1 is in a wait state, the main thread cannot execute down because the T1 is just waiting and not finished. */T1.join (); } Catch(interruptedexception e) {e.printstacktrace ();    } t2.start (); }    }classatest{BooleanFlag =true;  Public synchronized voidM1 () {System.out.println ("M1 Method Start" +Thread.CurrentThread ());  while(flag) {Try {                 This. Wait (10000);//this.wait ();}Catch(interruptedexception e) {e.printstacktrace (); } Flag=false; } System.out.println ("M1 Method End" +Thread.CurrentThread ()); }}

Let's talk about the join () method of the thread class:

the role of Join () is to allow the main thread to wait for the thread to end before it can continue to run , which is said to be relative to the thread, not to specify the main threads.

 PackageCom.fla.thread; Public classNotifytest { Public Static voidMain (string[] args) {FinalNtest n =Newntest (); Runnable run1=NewRunnable () {@Override Public voidrun () {n.m1 ();        }        }; Thread T1=NewThread (RUN1); Thread T2=NewThread (RUN1); Thread T3=NewThread (NewRunnable () {@Override Public voidrun () {n.m2 ();        }        });        T1.start ();        T2.start ();    T3.start (); }}classNtest {BooleanFlag =true ;  Public synchronized voidM1 () {System.out.println ("M1 method Starts" +thread.currentthread () + ", lock object hashcode:");  while(flag) {Try {                 This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println ("M1 Method Ends" +thread.currentthread () + ", lock object hashcode:"); }         Public synchronized voidm2 () {System.out.println ("M2 method starts" +thread.currentthread () + ", lock object hashcode:");//This.notifyall ();         This. Notify (); Flag=false ; }}

Notify () is a single thread that wakes up waiting on this object (consistent with the synchronization block lock object) on the monitor. , and Notifyall () is the one that wakes up all the threads waiting on this object monitor.

The difference between wait () and sleep ():

Wait () causes the current thread to be in a "waiting (blocking) state" and also gives the current thread the lock it holds and does not account for CPU resources.

Sleep () keeps the thread asleep for a period of time, taking up the CPU to sleep, and if it is in a synchronized code block, it will not release the locks held

Here, by the way, the yield () method of the Thread class.

Yield () is the function of concession. It allows the current thread to enter the "Ready state" from the "running state", allowing other waiting threads with the same priority to get execution, but there is no guarantee that other threads with the same priority will be able to gain execution after the current thread calls yield (), or that the current thread is entering the " Run status "continue running!

Three, wait and wake up

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.