This article mainly introduces the relevant information about the detailed explanation of the asynchronous callback instance completed by Java CountDownLatch. Friends in need can refer to the following
Detailed explanation of the asynchronous callback instance completed by Java CountDownLatch
Example code:
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(); final CountDownLatch latch = new CountDownLatch(2); executor.execute(new Task(latch)); executor.execute(new Task(latch)); executor.execute(() -> { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } onCompletion(); }); executor.shutdown(); } private static class Task implements Runnable { /** * CountDownLatch 是JDK提供的一个简单的线程监测工具 * 基于简单的计数,调用countDown()方法表明当前线程已经终止 * 在监测线程中调用await()方法,该方法会一直挂起直到所有其它线程终止 */ private final CountDownLatch latch; public Task(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { doSomeTask(); } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } } }
There are two points to add here:
1. If you start the thread using the main method, this There is no problem in calling the method. JDK will ensure that all threads are terminated before the main method exits. But if the main method is not the initiator of the asynchronous task (such as JUnit, Spring, Tomcat), the laucher will lose control of the thread once it is started. For example, in JUnit, after laucher submits the task, all processes will be considered completed, and other threads will be forcibly terminated.
2. Because of this, please use the correct Executor according to the environment. For example, in a web environment, you should use the thread pool managed by tomcat (or Spring) as the Executor, so as to ensure that the web application has control over the entire life cycle of the asynchronous task; if you choose the JDK thread pool What are the consequences? The task may be executed normally, but once you terminate the web-app, the executing asynchronous thread will not be killed normally, causing memory leaks or other unforeseen consequences.
The above is the detailed content of Java CountDownLatch completes asynchronous callback sample code sharing. For more information, please follow other related articles on the PHP Chinese website!