1. Requirements:
The thread loops 10 times, the main thread loops 100 times, so the interval loops 50 times. 2. Implementation:
Package com.amos.concurrent;
/** * @ClassName: Threadsynchronizedconnect * @Description: Using wait,notify to achieve communication between threads, demand: Child thread loop 10 times, main thread loop 100 times, so that the interval cycle 50 times. * @author: Amosli * @email: hi_amos@outlook.com * @date APR, 2014 4:39:44 PM/public class Threadsynchronizedconnec
t {public static void main (string[] args) {final Business Business = new Business ();
New Thread (New Runnable () {public void Run () {(int i = 0; i < i++) {
Business.sub (i);
}}). Start ();
for (int i = 0; i < i++) {business.main (i);
}/* Experience: Several methods to use common data (including synchronous locks) should be grouped together in the same class, so that it is easy to implement, high classified collection and the health of the program.
* * Static class Business {Private Boolean is_sub = true;
Child method public synchronized void sub (int i) {while (!is_sub) {//If not true, will wait, blocked state
try {this.wait (); } CATCH (interruptedexception e) {e.printstacktrace (); for (int j = 0; J < + j) {System.out.println ("Sub thread: + j +" Lo
OP: "+ i);
} Is_sub=false; This.notify ()//Wake Up Waiting thread}//Main method public synchronized void main (int i) {while is_sub
) {try {this.wait ();
catch (Interruptedexception e) {e.printstacktrace (); for (int j = 0; J < + j) {System.out.println ("main thread: + j +"
Loop: "+ i);
} is_sub=true;
This.notify (); }
}
}
3. Note:
It should be noted that several methods of using common data (including synchronous locks) should be grouped in the same class.
1. The conversion diagram between the four states of a thread may see that turning a thread from a running state to a blocking state requires only calling the wait () method, which joins the thread in the waiting state.
2. Then wake up the waiting state only need to call the Notify () method, if you want to wake all waiting threads, you can call the Notifyall () method.
3 Use the Synchronized keyword to synchronize the method so that it is not affected at run time.