异步FutureTask 简单使用

FutureTask

为Future 提供了基础实现,获取任务执行结果(get),和取消任务(cancel)。如果任务尚未完成,获取任务执行结果时会阻塞,一旦执行结束,任务就不能被重启(除非使用 runAndReset),Future 常用来风中callable和Runable,也可作为一个任务提交到线程池中执行。除了作为一个独立的类之外,此类也可以提供一些功能性函数,创建task使用,FutureTask 的线程安全由CAS保证

16546891241088

Future : 异步计算结果,查看异步线程是否执行完成,或者等待执行结果,或取消执行。

public interface Future<V> {
 boolean cancel(boolean mayInterruptIfRunning);
 boolean isCancelled();
 boolean isDone();
 V get() throws InterruptedException, ExecutionException;
 V get(long timeout, TimeUnit unit)
     throws InterruptedException, ExecutionException, TimeoutException;
}
方法作用
cancel取消异步任务
因为完成,或者其他原因取消失败返回 fasle
任务没有执行,停止任务,返回true
isCancelled判断任务是否被取消
任务结束(正常/异常)前取消 true
isDone任务完成(正常/异常) true
get获取任务结果,阻塞等带任务完成,任务被取消,抛出CancellationException
任务执行中出现异常抛出ExecutionException
阻塞等带过程中被中断抛出InterruptedException
get(long timeout, TimeUnit unit)带超时时间,阻塞等带过程中超时则抛出TimeoutException

基本使用 案例

@Slf4j
public class 异步编排 {

     public static ThreadPoolExecutor threadPool= new ThreadPoolExecutor(
                5, 10, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10),
                new ThreadFactory() {
        int i = 0;
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("异步任务测试 -- "+ i++);
            return thread ;
        }
    }
    , new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * 异步任务执行
     * @throws ExecutionException
     * @throws InterruptedException
     */
     @Test
     public void t01() throws ExecutionException, InterruptedException {

         CompletableFuture<Void> F1 = CompletableFuture.runAsync(() -> {
             try {
                 System.out.println("任务1执行前"+Thread.currentThread().getName());
                 Thread.sleep(5000);
                 System.out.println("任务1执行结束"); } catch (InterruptedException e) {
             }
         }, threadPool);
         System.out.println("主线任务执行中 阶段1");

         CompletableFuture<Void> F2 = CompletableFuture.runAsync(() -> {
             System.out.println("任务2执行前"+Thread.currentThread().getName());
             try {
                 Thread.sleep(3000);
             } catch (InterruptedException e) { }
             System.out.println("任务2执行结束");
         }, threadPool);

         System.out.println("主线任务执行中 阶段2");

         CompletableFuture<Void> F3 = null;
         boolean flag = true;
         if(flag){
              F3 = CompletableFuture.runAsync(() -> {
                 System.out.println("任务3执行前" + Thread.currentThread().getName());
                 try {
                     Thread.sleep(8000);
                 } catch (InterruptedException e) {}
                 System.out.println("任务3执行结束");
             }, threadPool);
         }else {

         }

         //等待所有任务执行结束  这里不能有null
         CompletableFuture<Void> fall = CompletableFuture.allOf(F1,F2,F3);
         fall.get();

         System.out.println("结束所有任务");
    }
}

异常处理案例

  @Test
     public void t02() throws  ExecutionException, InterruptedException {
        //
        CompletableFuture<Boolean> F1 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("任务1执行前"+Thread.currentThread().getName());
                Thread.sleep(5000);
                int i = 1/0;
                System.out.println("任务1执行结束"); } catch (InterruptedException e) {
            }
            return false;
        }, threadPool).handle( (result,e)->{
                 if(e!=null){
                     System.out.println(e.getMessage());
                     // 处理方式一 捕获异常直接抛出
                     //throw new RuntimeException("发生异常");
                 }
                 return  result;
        });

        CompletableFuture<Void> fall = CompletableFuture.allOf(F1);
        fall.get();
        // 处理方式二 判断是有异常 在做处理
        boolean completedExceptionally = fall.isCompletedExceptionally();
        System.out.println(completedExceptionally);
        
        System.out.println("结束所有任务");
     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值