版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/havebeenstand/article/details/83587177
1.Callable和Future适用于带有返回结果的多线程
示例
public class CallAndFutureStudy {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> result = threadPool.submit(new Callable<String>(
) {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "hello";
}
});
System.out.println("等待输出结果");
try {
System.out.println("取出返回结果:"+result.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.CompletionService(提交一组Callable)
处理多个带有返回结果的线程
public class CallAndFutureStudy {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
CompletionService<String> completionService = new ExecutorCompletionService<String>(threadPool);
for(int i = 0;i < 10;i++){
final int seq = i;
completionService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(new Random().nextInt(2000));
return "ThreadName"+Thread.currentThread().getName()+"执行,返回结果:"+seq;
}
});
}
for(int i = 0;i < 10;i++){
try {
System.out.println(completionService.take().get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
执行结果: