[1] Typical applications
Countdownlatch begin = new countdownlatch (1 );
Begin. Countdown (); // The lock count minus 1.
Begin. Await (); // blocking, etc. until begin is 0, or the current thread is interrupted by other threads
Http://man.ddvip.com/program/java_api_zh/java/util/concurrent/CountDownLatch.html
[2] thread, several methods that have never been clear
Here are the built-in methods of thread:
- Interrupt () interrupt thread.
The thread. Interrupt () method does not interrupt a running thread. In fact, this method throws an interruption signal when the thread is blocked, so that the thread can exit the blocking state. More specifically, if the thread is. wait, thread. join and thread. if sleep is blocked by one of the three methods, it will receive an interrupt exception (interruptedexception) to terminate the blocked state early.
- Sleep () sleep the currently executing thread (paused) at the specified time)
- Join () waits for the thread to terminate
- Yield () pause the currently executing thread object and execute other threads
Http://www.gznc.edu.cn/yxsz/jjglxy/book/Java_api/java/lang/Thread.html#interrupt ()
The method inherited from the object is as follows, which means that each object can be like this:
- Y () Wake up a single thread waiting on this object Monitor
- Yyall () Wake up all threads waiting on this object Monitor
- Wait () causes the current thread to wait until other threads call the notify () or notifyall () method of this object.
Wait () allows us to place threads in the "Sleep" state, while actively waiting for conditions to change. In addition, the thread will be awakened only when one notify () or notifyall () Change and check whether the conditions have changed.
Http://www.gznc.edu.cn/yxsz/jjglxy/book/Java_api/java/lang/Object.html#notify ()
[3] Wait () vs. Sleep ()/suspend ()
- For example, in synchronized (O), when sleep ()/suspend () is executed, both of them occupy the olock, while wait () can put the lock generously.
- Wait () only temporarily gives up the olock and uses it for other threads. In the end, it still needs to be withdrawn. When and how can it be recovered? Y ()/notifyall (). We will not discuss the situation of wait (timeout) for the moment.
- We can place Policy ()/policyall () in any synchronization method or within the synchronization block, regardless of whether the class is prepared for thread-related processing. In addition, we can only call wait () and Policy () in the synchronous method or block ().
[4] sample code of wait ()/notify:
Synchronized (B){
Try {
B. Wait ();
} Catch (interruptedexception e ){
}
}
Synchronized (this){
Try {
Notify ();
} Catch (...) {
}
}
Http://wenku.baidu.com/view/ed6dceea19e8b8f67c1cb9e8.html