Final Countdownlatch CDL = new Countdownlatch (1); New Thread (New Runnable () { @Override public void Run () { try { thread.sleep (); Cdl.countdown (); } catch (Exception e) { e.printstacktrace ();}}} ). Start (); Cdl.await (ten, timeunit.seconds);
Ideas:
Countdownlatch blocks the thread through the await method, the countdown method countdownlatch the value minus 1 per execution, until the Countdownlatch value is 0, and the blocking thread wakes up. The function of some callbacks is accomplished by Countdownlatch this feature.
@ Initialize default assignment of 1
The @CountDownLatch permanently blocks the thread through the await method until the value is 0, through a time-sensitive blocking thread, that is, when the time is timely, the thread is blocked, the time expires, and the blocking thread wakes automatically. This is similar to the 2 methods of inserting and dequeue with time parameters in a queue.
@ In 10s is blocked, as long as the Countdownlatch value is 0, the blocked thread immediately wakes up, starts to continue to execute downward, otherwise it can only continue to block until 10s expires after the blocking thread is automatically awakened.
Countdownlatch Calculator (with callback function)