Java thread methods of communication


/ **
* Examples of communication threads: 1-100 printing using two threads. Thread 1, Thread 2 alternately print
*
* relates to three methods:
* the wait (): This method, if implemented, the current thread enters the blocked state, and releases the synchronization monitor.
* Notify (): When you perform this method, you will wake up a thread of wait. If there are multiple threads wait, they wake up that high priority.
* NotifyAll (): When you perform this method, you will wake up all the wait thread.
*
* Description:
* 1.wait (), Notify (), notifyAll () method must be used in three blocks or synchronization code synchronization method.
* 2.wait (), notify () , notifyAll () method is called three must be synchronized block synchronization or synchronization monitor method.
* Otherwise, there will be IllegalMonitorStateException abnormal
* 3.wait (), notify () , notifyAll () method is defined in three java.lang.Object class.
*
* Interview questions: sleep () and wait () the similarities and differences?
* 1. same point: Once the method performed may be such that the current thread enters the blocked state.
* 2. Different points: 1 in different positions) declared two methods: the Thread class declaration sleep (), Object class declared in the wait ()
* 2) requires a different call: SLEEP () can be called at any desired scene . wait () must be used, or a block synchronization code synchronization method
* 3) monitors whether the release synchronization: If both methods are used in the synchronization code blocks or synchronization methods, sleep () will not release the lock, wait () releases the lock.
*

* /
Class the implements the Runnable {Number The
Private Number = int. 1;
Private Object obj = new new Object ();
@Override
public void RUN () {

the while (to true) {

the synchronized (obj) {

obj.notify ();

IF (Number <= 100) {

the try {
the Thread.sleep (10);
} the catch (InterruptedException E) {
e.printStackTrace ();
}

System.out.println (Thread.currentThread () getName () +. ":" + Number) ;
++ Number;

the try {
// such as call wait () method of the thread enters the blocked state
obj.wait ();
} the catch (InterruptedException E) {
e.printStackTrace ();
}

} the else {
BREAK;
}
}

}

}
}


public class {CommunicationTest
public static void main (String [] args) {
Number The Number Number The new new = ();
the thread new new the thread T1 = (Number);
the thread new new the thread T2 = (Number);

t1.setName ( "thread 1");
t2.setName("线程2");

t1.start();
t2.start();
}
}

Guess you like

Origin www.cnblogs.com/wpy188/p/12099895.html