Runable的缺点:没有返回值也不能抛出Checked Exception
Future的主要方法
get()
//get方法的行为取决于Callable任务的状态分五种情况
//1 任务正常完成,get立即返回结果
//2 任务尚未完成(未开始或进行中),get被阻塞直到任务完成
//3 任务被中断,get返回InterruptedException
//4 任务被取消,get返回CancellationException
//5 任务执行异常,get返回ExecutionException
get(long timeout, TimeUnit unit) //TimeoutException
//如果线程没有开始直接取消方法返回true.
//如果线程已完成或者已取消,返回false
//如果线程已经开始执行,那么将会根据参数是否中断执行的线程
boolean cancel(boolean mayInterruptIfRunning);
//是否完成,不管是否成功完成
boolean isDone();
线程池的submit方法返回Future
代码示例
/**
* 描述: 演示批量提交任务时,用List来批量接收结果
*/
public class MultiFutures {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(20);
ArrayList<Future> futures = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Future<Integer> future = service.submit(new CallableTask());
futures.add(future);
}
Thread.sleep(5000);
for (int i = 0; i < 20; i++) {
Future<Integer> future = futures.get(i);
try {
Integer integer = future.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
static class CallableTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return new Random().nextInt();
}
}
}
FuterTask获取Future
代码案例:
/**
* 描述: 演示FutureTask的用法
*/
public class FutureTaskDemo {
public static void main(String[] args) {
Task task = new Task();
FutureTask<Integer> integerFutureTask = new FutureTask<>(task);
// new Thread(integerFutureTask).start();
ExecutorService service = Executors.newCachedThreadPool();
service.submit(integerFutureTask);
try {
System.out.println("task运行结果:"+integerFutureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class Task implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("子线程正在计算");
Thread.sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
}
}