线程池简化了线程的管理工作,异步执行任务在大多数情况下是通过线程池去提交的,而Runnable接口和Callable接口都可以应用于线程池;
package java.util.concurrent;
public interface Executor {
// 执行任务
void execute(Runnable var1);
}
虽然Executor是个简单的接口,但它却为异步任务执行框架提供了基础,该框架能支持多种不同类型的任务执行策略。
ExecutorService接口定义了线程池的关闭接口shutdown(),还定义了可以有返回值的任务,也就是Callable。
public interface ExecutorService extends Executor {
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();
boolean awaitTermination(long var1, TimeUnit var3) throws InterruptedException;
<T> Future<T> submit(Callable<T> var1);
<T> Future<T> submit(Runnable var1, T var2);
Future<?> submit(Runnable var1);
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> var1) throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> var1, long var2, TimeUnit var4) throws InterruptedException;
<T> T invokeAny(Collection<? extends Callable<T>> var1) throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> var1, long var2, TimeUnit var4) throws InterruptedException, ExecutionException, TimeoutException;
}
Future是一个对异步任务进行交互、操作的接口。
(1) 能够取消异步执行中的任务;
(2) 判断异步任务是否执行完成;
(3) 获取异步任务完成后的执行结果;
package java.util.concurrent;
public interface Future<V> {
// 取消异步执行中的任务
boolean cancel(boolean var1);
boolean isCancelled();
// 判断异步任务是否执行成功
boolean isDone();
// 获取异步任务完成后的结果
V get() throws InterruptedException, ExecutionException;
V get(long var1, TimeUnit var3) throws InterruptedException, ExecutionException, TimeoutException;
}
package java.lang;
@FunctionalInterface
public interface Runnable {
// 这个run()方法返回值为void,没有受检异常的异常声明,出现异常只能内部捕获
void run();
}
package java.util.concurrent;
@FunctionalInterface
public interface Callable<V> {
// 这个call()方法有返回值,且声明了受检异常,可以直接抛出Exception异常
V call() throws Exception;
}
public class RunnableDemo2 {
// 通过线程池创建3个线程
private static ExecutorService executorService = Executors.newFixedThreadPool(3);
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 1、通过线程池的execute()方法提交异步执行任务,没有返回结果
executorService.execute(new RunnableTaskDemo());
// 2、通过线程池的submit()方法提交异步执行任务,有返回结果
Future<?> submit = executorService.submit(new RunnableTaskDemo());
// 获取返回结果
System.out.println(submit.get()); // null
}
}
public class CallableDemo2 {
// 通过线程池创建3个线程
private static ExecutorService executorService = Executors.newFixedThreadPool(3);
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 通过线程池的submit()方法提交异步执行任务,有返回结果
Future future = executorService.submit(new CallableTaskDemo());
// 获取返回结果
System.out.println(future.get());
}
}