Usage of keyword synchronized,wait,notify for inter-threading collaboration in Java

Source: Internet
Author: User

The wait/notify () keyword applies to a thread that notifies another thread that the required condition state is ready, most commonly used when a thread sleeps in a loop until the scene gets a specific condition. For example, a thread waits until one component in the queue is able to handle it, and another thread wakes up the waiting thread when the component is added to the queue.

The following code demonstrates collaboration between threads:

Package Thread_waitnotify;public class Productfactory {class Worker implements Runnable {private final OBJ ECT LockObject=NewObject (); Private volatile BooleanHaswork =false; PrivatevoidWaittaketask () { synchronized (lockobject) { while(!haswork) {                    Try{System.out.println ("Waiting in ..."); LockObject. wait                    (); } Catch(interruptedexception e) {e.printstacktrace ();            }} taketask (); }} PrivatevoidTaketask () {BooleanTmphaswork =false; synchronized (LockObject) {                if(haswork) tmphaswork=true; }            if(tmphaswork) {System.out.println ("Start doing the task ..."); Try{Thread.Sleep (3000); Synchronized (lockobject) {haswork=false; }                } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Task completed, rest after 3s exit ..."); Try{Thread.Sleep (3000); } Catch(interruptedexception e) {e.printstacktrace (); }                //System.out.println ("task complete, continue looking for the next task ...");                //Taketask ();}Else{System.out.println ("Temporarily no task, enter the waiting state ...");            Waittaketask (); }} PublicvoidNotifychange () {synchronized (lockobject) {haswork=true; System.out.println ("Get up and start ..."); LockObject. Notifyall ();//Wake up all threads waiting to get lockobject lock}} @Override publicvoidrun () {taketask (); }} public staticvoidMain (string[] args) throws Interruptedexception {worker worker=NewProductfactory ().NewWorker (); Thread Thread=NewThread (worker);        Thread.Start (); Thread.Sleep (3000);//Wake Child thread after main thread sleeps 3sWorker.notifychange ();//The main thread sets the semaphore in the child thread and wakes up the blocked threadthread. Join ();//The main thread blocks, waiting for the child thread to finish executing the main threadSystem.out.println ("Sub-thread execution completes, the main thread exits.") "); System.exit (0); }}

The execution results are as follows:

Talk about the relationship between synchronized and wait (), notify ():

1. There is not necessarily a wait,notify in a synchronized place.

2. There must be synchronized where there is wait,notify. This is because wait and notify are not thread classes, but are methods that each object has, and both methods are related to object locks, and there must be synchronized in place of locks.

Usage of keyword synchronized,wait,notify for inter-threading collaboration in Java

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.