如何等待在Java中完成多个任务? [英] How to wait for completion of multiple tasks in Java?
问题描述
在Java应用程序中实现并发的正确方法是什么?我知道Threads和东西,当然,我已经为Java编程了10年了,但没有太多的并发经验。
What is the proper way to implement concurrency in Java applications? I know about Threads and stuff, of course, I have been programming for Java for 10 years now, but haven't had too much experience with concurrency.
例如,我必须异步加载一些资源,并且只有在所有已加载后,我可以继续和做更多的工作。不用说,没有订单如何完成。
For example, I have to asynchronously load a few resources, and only after all have been loaded, can I proceed and do more work. Needless to say, there is no order how they will finish. How do I do this?
在JavaScript中,我喜欢使用 jQuery.deferred
p>
In JavaScript, I like using the jQuery.deferred
infrastructure, to say
$.when(deferred1,deferred2,deferred3...)
.done(
function(){//here everything is done
...
});
但是我在Java做什么?
But what do I do in Java?
推荐答案
如果我不使用parallel Streams或Spring MVC的TaskExecutor,我通常使用 CountDownLatch
。使用#任务实例化,对于完成其任务的每个线程减少一次。 CountDownLatch.await()
等待,直到锁存器为0.真正有用。
If I'm not using parallel Streams or Spring MVC's TaskExecutor, I usually use CountDownLatch
. Instantiate with # of tasks, reduce once for each thread that completes its task. CountDownLatch.await()
waits until the latch is at 0. Really useful.
href =https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html =nofollow> JavaDocs
Read more here: JavaDocs
这篇关于如何等待在Java中完成多个任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!