Public class asyncdemo { Private static void dosometask () {System.out.println ("Hello World"); } Private static void oncompletion () {System.out.println ("All Tasks finished"); } public static void Main (string[] args) {Executorservice executor = Executors.newcachedthreadpool ();FinalCountdownlatch latch =NewCountdownlatch (2); Executor.execute (NewTask (latch)); Executor.execute (NewTask (latch)); Executor.execute ((), {Try{latch.await (); }Catch(Interruptedexception e) {E.printstacktrace (); } oncompletion (); }); Executor.shutdown (); }Private Static class Task implements Runnable {/** * Countdownlatch is a simple thread monitoring tool provided by the JDK * based on a simple count, calling the countdown () method to indicate that the current thread has terminated * call await in the monitoring thread () Method, the method is suspended until all other threads are terminated. Private FinalCountdownlatch latch;Public Task (countdownlatch latch) { This. latch = latch; }@Override public void Run( ) {Try{Dosometask (); }Catch(Exception e) {E.printstacktrace (); }finally{Latch.countdown (); } } }}
Here are two points to add:
1. If you are a thread that is started with the main method, this method of invocation is not a problem, and the JDK will ensure that all threads terminate after the main method exits. However, if the main method is not the initiator of an asynchronous task (such as Junit,spring,tomcat), Laucher will lose control of the thread once it is started. As in JUnit, Laucher is considered complete after the task has been committed and other threads are forcibly terminated.
2. For this reason, please use the correct executor according to the environment. For example, in a Web environment, a tomcat (or spring)-managed thread pool should be used as a executor to ensure that the Web application has control over the entire life cycle of the asynchronous task; What happens if you use the thread pool of the JDK? The task may execute normally, and when you terminate Web-app, the asynchronous thread being executed will not be killed normally, causing a memory leak or other unforeseen consequences.
the thread in Executors.newcachedthreadpool () is Isdaemon true.
I've been working on it for 13 years and I've studied the use of countdownlatch coordination threads http://unmi.cc/countdownlatch-threads/.
Countdownlatch is a Java 1.5 added API, to Java 8 I will choose to use completablefuture, it to wait for all threads to complete can be simply called
Completablefuture.allof (completablefuture...completablefutures)
is the mechanism of the WAITALL () of other frameworks.
Java completes asynchronous callbacks with Countdownlatch