//这是callable与future的使用方式
public class CallableAndFuture {
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
//Future取得的结果类型和Callable返回的结果类型必须一致,这是通过泛型来实现的
//Callable要采用ExecutorSevice的submit方法提交,返回的future对象可以取消任务
Future<String> future =
threadPool.submit(
new Callable<String>() {
public String call() throws Exception {
Thread.sleep(2000);
return "hello";
};
}
);
System.out.println("等待结果");
try {
System.out.println("拿到结果:" + future.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的Future对象
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++){
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();
}
}
}
}
callable&future的使用
最新推荐文章于 2024-04-11 07:41:52 发布