Package com.czbk.thread;
/**
* Created by Chengtao on 17/12/3.
* Requirement: The child thread runs 10 times, then the main thread runs 100 times, runs 50 times sequentially
*
Wait (): Waits if the thread executes the wait method, the thread enters the waiting state, and the thread in the wait state must be called by another thread to wake up the Notify method.
Notify (): Wake-up thread pool waits for one of the threads.
Notifyall (): Wakes up the thread pool for all waiting threads.
Things to note about the wait and notify methods:
1. The wait method and the Notify method are the object objects.
2. The wait method and the Notify method must be used in a synchronous code block or in a synchronous function. Do not execute in synchronous code, will error
3. The wait method and the Notify method must be called by the lock object.
Wait (): If a thread executes the wait method, it waits in a thread pool with the lock object as an identifier.
At this point the thread frees the lock, enters the "temporary blocking" state, and calls the Notify method on the other thread to wake it up.
The thread that wakes up is "operational" and can be executed when the CPU is acquired.
Notify (): If a thread executes the Notify method, it wakes up one of the threads in the thread pool waiting for the lock object as an identifier.
The lock object is object;
Only the synchronous code block or the synchronous method has the lock;
The thread pool is created with the lock as an identifier
*/
Import Java.util.concurrent.atomic.AtomicInteger;
public class Thread04_traditionalthread_communication {
public static void Main (string[] args) {
Final Business business = new Business ();
New Thread (
New Runnable () {
public void Run () {
for (int i=1;i<=50;i++) {
Business.sub (i);
}
}
}
). Start ();
for (int i=1;i<=50;i++) {
Business.main (i);
}
}
}
Class Business {
Private Boolean bshouldsub = true;
Public synchronized void sub (int i) {
while (!bshouldsub) {
try {
This.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
for (int j=1;j<=10;j++) {
SYSTEM.OUT.PRINTLN ("Sub thread sequence of" + j + ", loop of" + i);
}
Bshouldsub = false;
This.notify ();
}
Public synchronized void Main (int i) {
while (bshouldsub) {
try {
This.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
for (int j=1;j<=100;j++) {
System.out.println ("Main thread sequence of" + j + ", loop of" + i);
}
Bshouldsub = true;
This.notify ();
}
}
Java multithreaded day04 thread communication