一、什么是Future?
在并发编程中,可以通过Future对象来异步获取结果。
使用Thread或runnable接口都不能获取异步的执行结果,因为他们没有返回值。而通过实现Callable接口和Future就可以获取异步执行的结果,当异步执行结束后,返回结果将保存在Future中。使用Future就可以让我们暂时去处理其他的任务而无需一直等待结果,等异步任务执行完毕再返回其结果。
二、Future中的get方法
1、get方法
获取任务结束后返回的结果,如果调用时,任务还没有结束,则会进行阻塞线程,直到任务完成。该阻塞是可以被打断的,打断的线程是调用get方法的线程,被打断后原任务会依旧继续执行。
V get() throws InterruptedException, ExecutionException;
2、指定时间的get方法
获取任务结束后返回的结果,如果调用时,任务还没有结束,则会进行阻塞线程,等待一定时间,如果在规定时间内任务结束则返回结果,否则抛出TimeoutException,超时后任务依旧会继续执行。该阻塞是可以被打断的,打断的线程是调用get方法的线程,被打断后原任务会依旧继续执行。
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
三、Future代码示例
步骤1:创建一个线程池
public class AsyncTaskExecutor {/*** 核心线程数*/private static final int corePoolSize = 10;/*** 最大线程数*/private static final int maxPoolSize = 30;/*** 空闲线程回收时间* 空闲线程是指:当前线程池中超过了核心线程数之后,多余的空闲线程的数量*/private static final int keepAliveTime = 100;/*** 任务队列/阻塞队列*/private static final int blockingQueueSize = 99999;private static final ThreadPoolExecutor executorPool = new ThreadPoolExecutor(corePoolSize,maxPoolSize,keepAliveTime,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(blockingQueueSize),new ThreadFactoryBuilder().setNameFormat("AsyncTaskThread" + "-%d").build(),new ThreadPoolExecutor.CallerRunsPolicy());/*** 异步任务执行** @param task*/public static void execute(Runnable task) {executorPool.execute(task);}/*** 异步执行任务Callable, 通过Future获取结果** @param task* @param <T>* @return*/public static <T> Future<T> submit(Callable<T> task) {return executorPool.submit(task);}/*** 异步执行任务Runnable,通过Future获取结果** @param task* @return*/public static Future<?> submit(Runnable task) {return executorPool.submit(task);}}
步骤2:编写测试类
@Testpublic void test2() {try {Future<String> future = AsyncTaskExecutor.submit(() -> {log.info("[Future Task] future task start...");try {//模拟任务执行Thread.sleep(5000);} catch (InterruptedException e) {log.info(e.getMessage());}log.info("[Future Task] future task end...");return "Task completed...";});//执行其他任务log.info("[Main Thread] main thread is running...");//使用future阻塞等待任务完成,并获取结果String futureResult = future.get();log.info("[Main Thread] {}", futureResult);}catch (Exception e) {e.printStackTrace();}}
步骤3:查看结果
2024-05-28 10:58:23.633 INFO 1184 --- [ main] com.example.demo.dao.UserDaoTest : [Main Thread] main thread is running...
2024-05-28 10:58:23.633 INFO 1184 --- [yncTaskThread-0] com.example.demo.dao.UserDaoTest : [Future Task] future task start...
2024-05-28 10:58:28.633 INFO 1184 --- [yncTaskThread-0] com.example.demo.dao.UserDaoTest : [Future Task] future task end...
2024-05-28 10:58:28.634 INFO 1184 --- [ main] com.example.demo.dao.UserDaoTest : [Main Thread] Task completed...
四、ListenableFuture
public class AsyncTaskExecutor {/*** 核心线程数*/private static final int corePoolSize = 10;/*** 最大线程数*/private static final int maxPoolSize = 30;/*** 空闲线程回收时间* 空闲线程是指:当前线程池中超过了核心线程数之后,多余的空闲线程的数量*/private static final int keepAliveTime = 100;/*** 任务队列/阻塞队列*/private static final int blockingQueueSize = 99999;private static final ThreadPoolExecutor executorPool = new ThreadPoolExecutor(corePoolSize,maxPoolSize,keepAliveTime,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(blockingQueueSize),new ThreadFactoryBuilder().setNameFormat("AsyncTaskThread" + "-%d").build(),new ThreadPoolExecutor.CallerRunsPolicy());/*** 创建一个ListeningExecutorService,用于执行异步任务* (通过submit提交任务,以ListenableFuture获取结果)*/private static final ListeningExecutorService LISTENING_EXECUTOR = MoreExecutors.listeningDecorator(executorPool);/*** 异步任务执行** @param task*/public static void execute(Runnable task) {executorPool.execute(task);}/*** 异步执行任务Callable, 通过ListenableFuture获取结果** @param task* @param <T>* @return*/public static <T> ListenableFuture<T> submit(Callable<T> task) {return LISTENING_EXECUTOR.submit(task);}/*** 异步执行任务Runnable,通过Future获取结果** @param task* @return*/public static ListenableFuture<?> submit(Runnable task) {return LISTENING_EXECUTOR.submit(task);}
}
@Testpublic void test2() {try {
// sqlSession = MybatisUtils.getSqlSession();
// UserDao mapper = sqlSession.getMapper(UserDao.class);
// boolean x = mapper.addUser(new User(6, "eeee", "eeee", "school666"));
// if (x == true) {
// log.info("OK..........");
// mapper.getUserList().forEach(user -> System.out.println(user));
// }// //步骤1:创建异步任务
// CommonTask task = new CommonTask(1L, ModelEnum.Chinese);
// //步骤2:调用线程池异步执行任务
// AsyncTaskExecutor.execute(task);
// log.info("main thread over...");CompletableFuture<School> schoolFuture = new CompletableFuture<>();ListenableFuture<School> listenableFuture1 = AsyncTaskExecutor.submit(() -> {try {//模拟任务执行Thread.sleep(2000);} catch (InterruptedException e) {log.info(e.getMessage());}return new School("DSchool");});ListenableFuture<School> listenableFuture2 = AsyncTaskExecutor.submit(() -> {try {//模拟任务执行Thread.sleep(2000);} catch (InterruptedException e) {log.info(e.getMessage());}return new School("ESchool");});Futures.successfulAsList(listenableFuture1, listenableFuture2).get();School resSchool = listenableFuture1.get(3000, TimeUnit.MILLISECONDS);log.info("[Main Thread] result is {}", JSON.toJSON(resSchool));}catch (Exception e) {e.printStackTrace();}}