Callable是一个类似于Runnable的接口,只是Callable可以返回一个任务执行后的结果。
Future用于接收Callable执行任务完成后返回的数据
public class CallableAndFutureTest
{
public static void main(String[] args)
{
ExecutorService threadPool = Executors.newSingleThreadExecutor();
/**
* 1、Callable是一个类似于Runnable的接口,只是Callable可以返回一个任务执行后的结果。
* 我理解的相当于回调函数一样;
* 2、Future用于接收Callable执行任务完成后返回的数据
*/
Future<Long> future = threadPool.submit(new Callable<Long>()
{
@Override
public Long call() throws Exception
{
System.out.println("Running...");
Thread.sleep(1000);
//返回执行本次任务的线程Id
return Thread.currentThread().getId();
}
});
threadPool.shutdown();
System.out.println("等待结果...");
try
{
System.out.println("获取结果:" + future.get());
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ExecutionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用CompletionService实现提交一组Callable任务, 然后循环接收已经完成任务的返回信息
public class CompletionServiceTest
{
public static void main(String[] args)
{
/*
* 使用CompletionService实现提交一组Callable任务, 然后循环接收已经完成任务的返回信息
*/
ExecutorService threadpool = Executors.newFixedThreadPool(10);
CompletionService<Long> completionService = new ExecutorCompletionService<Long>(
threadpool);
//提交任务
for (int i = 0; i < 10; i++)
{
completionService.submit(new Callable<Long>()
{
@Override
public Long call() throws Exception
{
System.out.println("执行中...");
Thread.sleep(new Random().nextInt(5000));
return Thread.currentThread().getId();
}
});
}
threadpool.shutdown();
System.out.println("等待结果...");
//获得任务执行的返回值
for(int i = 0; i < 10; i++)
{
try
{
System.out.println("收到结果:");
System.out.println(completionService.take().get());
System.out.println("===========================");
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ExecutionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}