Java Foundation---->java Multi-threaded use (eight)

Source: Internet
Author: User
Tags object object

Learn about the use of the Wait method and the Notify method in Java multi-threading.

Use of the wait and notify methods a simple instance of wait and notify
ImportJava.util.concurrent.TimeUnit; Public classWaitthreadtest { Public Static voidMain (string[] args)throwsException {Object Object=NewObject (); NewWaitthread (Object). Start (); TimeUnit.SECONDS.sleep (2);//wake up after 2 seconds        NewNotifythread (Object). Start (); }    Static classWaitthreadextendsThread {PrivateObject object; Waitthread (Object object) { This. Object =object; } @Override Public voidrun () {synchronized(object) {Try{System.out.println ("Before wait.");                    Object.wait (); System.out.println ("After wait."); } Catch(interruptedexception e) {e.printstacktrace (); }            }        }    }    Static classNotifythreadextendsThread {PrivateObject object; Notifythread (Object object) { This. Object =object; } @Override Public voidrun () {synchronized(object) {System.out.println ("Before notify.");                Object.notify (); System.out.println ("After notify."); }        }    }}

The results of the operation are as follows:

Before Wait.before notify.after notify.after wait.

If you modify Object.wait () to object.wait (1), the result of the operation is as follows:

Before Wait.after Wait.before notify.after notify.

Friendship Link

Java Foundation---->java Multi-threaded use (eight)

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.