Thread basics-wait (), notify application example

Source: Internet
Author: User

 


In this example, two threads are implemented, and each thread outputs a number ranging from 1 to 100. The first thread outputs 1-10, stops, notifies the second thread to output 1-10, the second thread to stop, and notifies the first thread to output 11-20... the main point of implementation is that in Java, each Object has an Object lock flag associated with it. When A thread A calls A synchronized code of an Object, first, it needs to obtain the object lock flag associated with this object, and then execute the corresponding code. After the execution ends, it returns the object lock flag to the object. Therefore, when thread A executes synchronized code, if thread B needs to execute A synchronized code of the same object (not necessarily the same as thread ), it will not continue until thread A finishes executing ....

How to Use wait () notify () notifyAll ()?

During the execution of synchronized code, the thread can call the wait () method of the object, release the object lock flag, enter the waiting state, and call y () or yyall () method to notify other threads that are waiting. Y () notifies the first thread in the waiting queue. notifyAll () notifies all threads in the waiting queue.

 
   
Package jdeveloper. study;
/**
 * Title:Jdevelopers Java Projdect
 * Description:N/
 * Copyright:Copyright (c) 2001
 * Company:SohoHttp://www.ChinaJavaWorld.com
 * @ Author jdeveloper@21cn.com
 * @ Version 1.0
 */
Import java. lang. Runnable;
Import java. lang. Thread;
Public class DemoThread implements Runnable {
Public DemoThread (){
TestThread testthread1 = new TestThread (this, "1 ");
TestThread testthread2 = new TestThread (this, "2 ");
Testthread2.start ();
Testthread1.start ();
}
Public static void main (String [] args ){
DemoThread demoThread1 = new DemoThread ();
}
Public void run (){
TestThread t = (TestThread) Thread. currentThread ();
Try {
If (! T. getName (). inclusignorecase ("1 ")){
Related Article

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.