本文可作为传智播客《张孝祥-Java多线程与并发库高级应用》的学习笔记。
在前面写的代码中,所有的任务执行也就执行了,run方法的返回值为空。
这一节我们说的Callable就是一个可以带返回值的线程模型。而它的返回值由Future接着。java.util.concurrent Interface Callable<V>接口里面只有一个call方法,参数为空,返回值为T。
public class FutureTask<V> extends Object implements RunnableFuture<V>其中RunnableFuture实现了Runnable接口。
public static void main(String[] args) {
Callable<Integer> callable = new Callable<Integer>() {
public Integer call() throws Exception {
int a=new Random().nextInt(100);
System.out.println(a+" ss");
return a;
}
};
FutureTask<Integer> ft=new FutureTask<Integer>(callable);
// for (int i = 0; i < 5; i++)
// new Thread(ft).start();
new Thread(ft).start();
try {
System.out.println("得到结果 "+ft.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}运行结果我们再看看Future类
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> future =
threadPool.submit(
new Callable<String>() {
public String call() throws Exception {
Thread.sleep(2000);
return "hello";
};
}
);
System.out.println("等待结果");
//这里应该有trycatch
System.out.println("拿到结果:" + future.get());
}结果不再赘述。public static void main(String[] args) {
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
for(int i=1;i<=10;i++){
final int seq = i;
completionService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return seq;
}
});
}
for(int i=0;i<10;i++){
System.out.println(completionService.take().get());
//上面本应该有trycatch
}
threadPool2.shutdown();
}运行结果3
9
1
6
8
4
7
10
5
2
completionService.submit了10个任务,completionService本身也不知道那个任务先执行完。completionService.take()就是获得已经执行完的那个任务的Future。
感谢glt
原文:http://blog.csdn.net/dlf123321/article/details/42984985