这是一个很好的方法来使用java.util.concurrent.FutureTask? [英] Is it a good way to use java.util.concurrent.FutureTask?
问题描述
首先,我必须说我对API java.util.concurrent非常陌生,所以也许我所做的是完全错误的。
First of all, I must say that I am quite new to the API java.util.concurrent, so maybe what I am doing is completely wrong.
我有一个基本上运行2个独立处理的Java应用程序(称为 myFirstProcess , mySecondProcess >),但这些处理必须同时运行。
I have a Java application that basically runs 2 separate processing (called myFirstProcess, mySecondProcess), but these processing must be run at the same time.
所以,我试图这样做:
public void startMyApplication() {
ExecutorService executor = Executors.newFixedThreadPool(2);
FutureTask<Object> futureOne = new FutureTask<Object>(myFirstProcess);
FutureTask<Object> futureTwo = new FutureTask<Object>(mySecondProcess);
executor.execute(futureOne);
executor.execute(futureTwo);
while (!(futureOne.isDone() && futureTwo.isDone())) {
try {
// I wait until both processes are finished.
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
logger.info("Processing finished");
executor.shutdown();
// Do some processing on results
...
}
myFirstProcess 和 mySecondProcess 是实现 Callable< Object>
的类, call()方法。
myFirstProcess and mySecondProcess are classes that implements Callable<Object>
, and where all their processing is made in the call() method.
它工作相当好,但我不知道这是正确的方法。
是一个很好的方法来做我想要的吗?
It is working quite well but I am not sure that it is the correct way to do that. Is a good way to do what I want? If not, can you give me some hints to enhance my code (and still keep it as simple as possible).
推荐答案
如果没有,你可以给我一些提示来增强我的代码最好使用 get()
方法。
You'd be better off using the get()
method.
futureOne.get();
futureTwo.get();
这两个都等待线程完成处理的通知,这将节省您的忙等待
Both of which wait for notification from the thread that it finished processing, this saves you the busy-wait-with-timer you are now using which is not efficient nor elegant.
作为奖励,你有API get(long timeout,TimeUnit单位)
,它允许您定义线程睡眠并等待响应的最长时间,否则继续运行。
As a bonus, you have the API get(long timeout, TimeUnit unit)
which allows you to define a maximum time for the thread to sleep and wait for a response, and otherwise continues running.
See the Java API for more info.
这篇关于这是一个很好的方法来使用java.util.concurrent.FutureTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!