java中的异步任务处理和Feature接口

简介

Java并发包提供了一套框架,大大简化了执行异步任务所需要的开发。框架引入了“执行服务”的概念,封装了任务执行的细节,对任务提交者而言,他可以关注任务本身,如提交任务、获取结果、取消任务。而不用关注任务执行的细节。

基本接口

①Runnable和Callable: 表示要执行的任务

②Excecutor和ExecutorService: 表示执行服务

③Future: 表示异步执行的结果

示例

import java.util.concurrent.*;


// ①要执行的异步任务
class Task implements Callable<Double> {
    @Override
    public Double call() {
        //以异步方式在新的线程中执行耗时的操作
        try {
            System.out.println("doSomeLongComputation start");
            Thread.sleep(3000);
            System.out.println("doSomeLongComputation end");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return 1.0;
    }
}

public class MyTestFeature {
    void doSomethingElse() {
        try {
            System.out.println("doSomethingElse start");
            Thread.sleep(1000);
            System.out.println("doSomethingElse end");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void testFeature() {
        //②执行服务
        ExecutorService executor = Executors.newCachedThreadPool();
        //③异步任务结果
        Future<Double> futureRate = executor.submit(new Task());

        //异步操作进行的同时你可以做其他的事情
        doSomethingElse();

        try {
            //获取异步操作的结果,如果最终被阻塞,无法得到结果,那么在最多等待5秒钟之后退出
            Double result = futureRate.get(5, TimeUnit.SECONDS);
            System.out.println("Result->" + result);
        } catch (ExecutionException e) {
            // 计算抛出一个异常
            e.printStackTrace();
        } catch (InterruptedException ie) { // 当前线程在等待过程中被中断
            System.out.println("InterruptedException");
        } catch (TimeoutException te) { // 在Future对象完成之前超过已过期
            System.out.println("TimeoutException");
        }
        executor.shutdown();
    }

    public static void main(String[] args) {
        MyTestFeature case1 = new MyTestFeature();
        case1.testFeature();
    }
}

执行

doSomethingElse start
doSomeLongComputation start
doSomethingElse end
doSomeLongComputation end
Result->1.0

说明

①有两个关闭方法:shutdown和shutdownNow。区别:shutdown不再接受新任务,但已经提交的任务(即使未开始)会继续执行;shutdownNow不仅不接受新任务,且会终止已提交但未执行的任务。

②例子中如果executor不关闭,主线程结束后,还得等子线程等待很长时间结束

 

参考

https://blog.csdn.net/wangdong5678999/article/details/81837387

posted @ 2023-10-08 20:17  jihite  阅读(222)  评论(0编辑  收藏  举报