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 ")){