当前位置: 首页 > news >正文

java中Future使用详细介绍

一、什么是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();}}
http://www.lryc.cn/news/355841.html

相关文章:

  • docker和containerd的区别
  • 汇编实现流水灯
  • SQL生成序列浅析
  • 24年gdcpc省赛C题
  • 以梦为马,不负韶华(3)-AGI在企业服务的应用
  • Xshell 使用
  • 【yijiej】mysql报错 之 报错:Duplicate entry 字段 for key ‘表名.idx_字段’
  • 解决npm卡死,无法安装依赖
  • 速卖通测评揭秘:如何选择安全的渠道操作
  • ping不通ip的解决方法
  • Linux x86_64 UEFI 启动
  • 妙解设计模式之适配器模式
  • 【Linux】Linux下centos更换国内yum源
  • HTML静态网页成品作业(HTML+CSS)——动漫熊出没介绍网页(3个页面)
  • 算法训练营day42
  • 【Vue】自动导入组件
  • mfc140u.dll丢失的解决方法有哪些?怎么全面修复mfc140u.dll文件
  • MySQL8报错Public Key Retrieval is not allowedz 怎么解决?
  • 海外动态IP代理如何提高效率?
  • 解析边缘计算网关的优势-天拓四方
  • 计算机原理 知识回顾
  • WPF 如何调试
  • URL跳转
  • Spring Boot集成rss快速入门demo
  • 重学java 49 List接口
  • 【html+css(大作业)】二级菜单导航栏
  • 算法基础之集合-Nim游戏
  • Diffusion Model, Stable Diffusion, Stable Diffusion XL 详解
  • 智能奶柜:重塑牛奶零售新篇章
  • 源代码防泄密--沙盒技术安全风险分析