简体   繁体   English

Java。 按完成顺序连接线程,并在每次连接后运行一个钩子

[英]Java. Join threads in order of completion and run a kind of a hook after each join

I want to be able to join each thread at once it finished its job. 我希望能够在每个线程完成工作后立即加入。 In the code example below main thread will wait as long as each thread will run by their order in the list and only then next thread will be joined. 在下面的代码示例中,主线程将等待,直到每个线程将按其在列表中的顺序运行,然后才连接下一个线程。

    List<Thread> threads = new ArrayList<>();

    threads.add(new Thread(new Worker(), "T1"));
    threads.add(new Thread(new Worker(), "T2"));
    threads.add(new Thread(new Worker(), "T3"));

    threads.forEach(Thread::start);

    threads.forEach(thread -> {
        try {
            thread.join();
            someHook();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

You should use a CompletableFuture 您应该使用CompletableFuture

    ExecutorService e = Executors.newFixedThreadPool(3);
    ExecutorService single = Executors.newSingleThreadExecutor();
    List<CompletableFuture<?>> futures = new ArrayList<>();
    futures.add(CompletableFuture.runAsync(new Worker(), e).thenRunAsync(this::someHook, single));
    futures.add(CompletableFuture.runAsync(new Worker(), e).thenRunAsync(this::someHook, single));
    futures.add(CompletableFuture.runAsync(new Worker(), e).thenRunAsync(this::someHook, single));

    futures.forEach(f -> f.get()); // try-catch left out for brevity

In this case you will run 3 tasks async and have a single thread force each hook to be done sequentially. 在这种情况下,您将异步运行3个任务,并有一个线程强制每个挂接按顺序完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM