代码之家  ›  专栏  ›  技术社区  ›  Homewrecker

Java 8并发-等待任务关闭执行器

  •  4
  • Homewrecker  · 技术社区  · 8 年前

    我正在尝试Java 8并发的第一步。 在下面的代码示例中,由于my tasks睡眠2秒,因此引发了一个异常。关机功能等待5秒钟后终止。因此,只执行两个循环。是否有一个动态的解决方案来代替计算执行可能需要的最长时间并调整waitTermination()方法的值?

    public class Application {
    
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(1);
    
            IntStream.range(0, 10).forEach(i ->
                    executor.submit(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(2);
                            System.out.println("Hello");
                        } catch (InterruptedException e) {
                            throw new IllegalStateException("Task interrupted", e);
                        }
                    })
            );
    
            shutdown(executor);
        }
    
        private static void shutdown(ExecutorService executor) {
            try {
                executor.shutdown();
                executor.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                System.err.println("tasks interrupted");
            } finally {
                if (!executor.isTerminated()) {
                    System.err.println("cancel non-finished tasks");
                }
                executor.shutdownNow();
            }
        }
    
    1 回复  |  直到 8 年前
        1
  •  5
  •   shazin    8 年前

    除了@AdamSkyWalker提到的之外,您还可以使用CountdownClast,因为您已经知道线程数(本例中为10个)。

    public static void main(String[] args) throws Exception {
            ExecutorService executor = Executors.newFixedThreadPool(1);
            final CountDownLatch latch = new CountDownLatch(10);
    
            IntStream.range(0, 10).forEach(i ->
                    executor.submit(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(2);
                            System.out.println("Hello");
                        } catch (InterruptedException e) {
                            throw new IllegalStateException("Task interrupted", e);
                        } finally {
                            latch.countDown();
                        }
                    })
            );
    
            latch.await();
    
    
        }
    }
    

    我写了一个 post 回头再比较一下 CountDownLatch , Semaphore CyclicBarrier 这对你很有帮助。