futuretask java,这是一个很好的方法来使用java.util.concurrent.FutureTask?

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.

What do I want to do?

I have a Java application that basically runs 2 separate processing (called myFirstProcess, mySecondProcess), but these processing must be run at the same time.

So, I tried to do that:

public void startMyApplication() {

ExecutorService executor = Executors.newFixedThreadPool(2);

FutureTask futureOne = new FutureTask(myFirstProcess);

FutureTask futureTwo = new FutureTask(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 and mySecondProcess are classes that implements Callable, 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).

解决方案

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值