您的位置:首页 > 其它

Callable&&Future的基本使用

2015-12-01 14:56 405 查看

ExecutorService的submit

ExecutorService的submit方法可以接收一个Callable<T>对象,并且返回一个Future<V> 。

public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
public interface Future<V> {
//取消执行的任务
boolean cancel(boolean mayInterruptIfRunning);
//如果任务在未完成之前取消,则返回true
boolean isCancelled();
//任务完成,返回true
boolean isDone();
//	等待返回的结果
V get() throws InterruptedException, ExecutionException;
//按照指定的时间去获取执行的结果,
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
class MyCallable1 implements Callable<String> {
public String call() throws Exception {
return " method call is running";
};
}
@Test
public void test01() throws Exception {
// 1、创建线程池
ExecutorService threadPool = Executors.newSingleThreadExecutor();
// 2、提交任务、获取返回值
Future<String> future = threadPool.submit(new MyCallable1());
//3、输出返回值
System.out.println(future.get());
threadPool.shutdown();
}

CompletionService

可以提交一组Callable,并使用take方法返回已完成一个Callable任务对应的Future对象。
class MyCallable2 implements Callable<Integer>  {
private int seq ;
public MyCallable2(int seq){
this.seq = seq;
}
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return seq;
}
}
@Test
public void test02() throws Exception {
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2);
for (int i = 1; i <= 10; i++) {
completionService.submit(new MyCallable2(i));
}
for (int i = 0; i < 12; i++) {
System.out.println("start >> "+i);
System.out.println(completionService.take().get());
System.out.println("end >> "+i);
//如果没有拿到结果,会阻塞在那里。
}
threadPool2.shutdown();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: