FutureTask是线程的异步计算。如果有多个线程,每个线程都要花很多时间计算,而且所花时间不同,最后要统计,就要用到此类。
此类有个done方法,等call完后,执行此方法。
代码:
package com.concurrent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import junit.framework.TestCase;
public class TestFutureTask extends TestCase {
private static final Random random = new Random();
private static final int COUNT = 5;
public void testFutureTask() {
ExecutorService executorService = Executors.newFixedThreadPool(COUNT);
List<FutureTask<Integer>> list = new ArrayList<FutureTask<Integer>>();
for (int i = 0; i < COUNT; i++) {
final int index = i;
FutureTask<Integer> ft = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int result = random.nextInt(10);
System.out.println("call " + index + ", result = " + result);
return result;
}
}) {
@Override
protected void done() {
System.out.println("done " + index);
}
};
list.add(ft);
executorService.submit(ft);
}
int sum = 0;
for (FutureTask<Integer> ft : list) {
try {
sum += ft.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println("sum = " + sum);
executorService.shutdown();
}
}
输出:
call 0, result = 6
call 1, result = 5
call 2, result = 4
done 1
done 2
done 0
call 3, result = 2
done 3
call 4, result = 9
done 4
sum = 26