并行查询的超时时间设置

众所周知,并行查询可以提高程序运行效率。主线程需要等待所有子线程把数据查询出结果,如果没有设置超时时间,就需要主线程就会一直阻塞到那里,从而占用服务器资源,那么如何设置超时时间呢?

1.在SpringBoot项目中引入线程池

java 复制代码
@EnableAsync
@Configuration
public class ThreadPoolsConfig {

    @Value("${AsyncTaskExecutor.corePooleSize:6}")
    private Integer corePooleSize;
    @Value("${AsyncTaskExecutor.maxPoolSize:15}")
    private Integer maxPoolSize;
    @Value("${AsyncTaskExecutor.queueCapacity:20000}")
    private Integer queueCapacity;

    /**
     * 自定义线程池
     */
    @Bean("myTaskExecutor")
    public AsyncTaskExecutor getMyTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("TaskThreadExec--");
        executor.setCorePoolSize(corePooleSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // 放弃等待队列中最旧的任务来添加新的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        return executor;
    }

}

2.使用java.util.concurrent.CompletableFuture进行并行查询(未设置超时时间)

java 复制代码
        CompletableFuture[] asyncList = new CompletableFuture[]{
                CompletableFuture.runAsync(() -> queryDataA(), asyncTaskExecutor),
                CompletableFuture.runAsync(() -> queryDataB(), asyncTaskExecutor)
        };
        CompletableFuture.allOf(asyncList).join();

3.使用java.util.concurrent.CompletableFuture进行并行查询(设置超时时间)

java 复制代码
        CompletableFuture[] asyncList = new CompletableFuture[]{
                CompletableFuture.runAsync(() -> queryDataA(), asyncTaskExecutor),
                CompletableFuture.runAsync(() -> queryDataB(), asyncTaskExecutor)
        };

        try {
         	CompletableFuture.allOf(asyncList).get(3, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            System.err.println("多线程查询"+e.getMessage());
            Thread.currentThread().interrupt();
        }

需要说明的是,这里的interrupt方法也可以不调用。

interrupt方法的作用如下:

线程A在执行sleep,wait,join时,线程B调用线程A的interrupt方法,的确这一个时候A会有InterruptedException 异常抛出来。

但这其实是在sleep、wait、join这些方法内部会不断检查中断状态的值,而自己抛出的InterruptedException

java 复制代码
import java.util.Date;

public class MyThread extends Thread{

    @Override
    public void run() {
        while (!isInterrupted()){
            System.out.println(new Date());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        myThread.start();

        //1秒后打断子线程
        Thread.sleep(1000);
        myThread.interrupt();
    }
}
相关推荐
deng-c-f17 小时前
Linux C/C++ 学习日记(53):原子操作(二):实现shared_ptr
开发语言·c++·学习
wanghowie17 小时前
01.07 Java基础篇|函数式编程与语言新特性总览
java·开发语言·面试
Cricyta Sevina17 小时前
Java IO 基础理论知识笔记
java·开发语言·笔记
MyBFuture17 小时前
C#接口与抽象类:关键区别详解
开发语言·c#·visual studio
晨晖218 小时前
简单排序c语言版
c语言·开发语言
小萌新上大分18 小时前
java线程通信 生产者消费者,synchronized,,ReentrantLock,Condition(笔记备份)
java·多线程·lock·java线程间通信的方式·reentrantlock使用·生产者消费者问题java·java多线程与高并发
それども18 小时前
Spring Bean 的name可以相同吗
java·后端·spring
MediaTea18 小时前
大学 Python 编程基础(合集)
开发语言·python
墨雪不会编程18 小时前
C++ string 详解:STL 字符串容器的使用技巧
java·开发语言·c++
Lucky GGBond18 小时前
实践开发:老系统新增字段我是如何用枚举优雅兼容历史数据的
java