java后台请求接口超时的处理

以上内容出自:https://www.cnblogs.com/hzjjames/p/java_timeout.html

但是遇到一个idea自动提示的错误,如下图:

线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。 说明:Executors各个方法的弊端:

官方更推荐用ThreadPoolExecutor的方式手动创建线程池。

于是将上面的代码改为:

ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(20);
ExecutorService executorService = new ThreadPoolExecutor(3, 5, 50, TimeUnit.MILLISECONDS, queue);

警告消除。

        ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(20);
        ExecutorService executorService = new ThreadPoolExecutor(3, 5, 50, TimeUnit.MILLISECONDS, queue);

//        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
        Future<String> future = executorService.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("任务被中断");
                }
                return "OK";
        });
        try {
            future.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            // 参数为true则会强制interrupt中断
            future.cancel(true);
            e.printStackTrace();
            System.out.println("任务超时");
            return "任务超时";
        } finally {
            System.out.println("清理资源");
        }

代码解读:

一、callable是函数式接口,可以用lambda表达式简化书写:

二、future.cancle();

future.cancel(true);参数可以为false和true,参数为true则会强制interrupt中断正在执行的任务。

控制台打印任务中断异常:

三、TimeUnit.SECONDS.sleep(10);

底层调用的还是Thread.sleep()方法:

参考链接:

1.futureTask解读:https://www.cnblogs.com/maypattis/p/5827671.html

2.Executor、Executors、ExecutorService:https://blog.csdn.net/weixin_40304387/article/details/80508236

3.Thread.sleep()和TimeUnit.SECONDS.sleep()的区别与联系https://www.cnblogs.com/sanhuan/p/4826401.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章