线程池基础使用案例

2023-11-27 12:46:08 浏览数 (1)

创建一个线程池的使用工具类

线程池使用工具类

代码语言:java复制
import java.util.concurrent.*;


public class ThreadPoolUtil {

   /* public static ExecutorService getThreadPoolExecutor(int size, int maxSize){
        return new ThreadPoolExecutor(
                size,
                maxSize,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
    }
    public static ExecutorService getThreadPoolExecutor(int size, int maxSize) {
        int keepAliveTime = 60; // 线程的最大空闲时间(单位:秒)
        int queueCapacity = 100; // 阻塞队列的容量

        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                size, maxSize, keepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(queueCapacity));

        // 设置拒绝策略为调用线程执行任务
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        return threadPoolExecutor;
    }*/
    public static ExecutorService getThreadPoolExecutor(int size, int maxSize) {
        // 根据实际需求进行调整
        int keepAliveTime = 60; // 线程的最大空闲时间(单位:秒)
        int queueCapacity = 100; // 阻塞队列的容量
        ThreadFactory threadFactory = Executors.defaultThreadFactory(); // 默认线程工厂
        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy(); // 拒绝策略

        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                size, maxSize, keepAliveTime, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueCapacity), threadFactory, rejectedExecutionHandler);

        // 设置核心线程数和最大线程数相等,避免线程数量动态调整
        threadPoolExecutor.setCorePoolSize(size);

        return threadPoolExecutor;
    }
}

使用线程池

代码语言:java复制
 @Test
    public void threadTest() throws ExecutionException, InterruptedException {
        ExecutorService threadPoolExecutor = ThreadPoolUtil.getThreadPoolExecutor(5, 10);
        long start = System.currentTimeMillis();
        HashMap<String, Object> hashMap = new HashMap<>();

        CompletableFuture<Void> emailInfo=CompletableFuture.runAsync(() -> {
            PageHelper.startPage(1,1000);
            List<EmailInfo> list = iEmailInfoService.list();
            hashMap.put("emailInfo",list);

        },threadPoolExecutor);
        CompletableFuture<Void> Attachment=CompletableFuture.runAsync(() -> {
            PageHelper.startPage(1,1000);
            List<Attachment> list2 = iAttachmentService.list();
            hashMap.put("Attachment",list2);
        },threadPoolExecutor);
       //等待线程执行完毕 获取结果
        CompletableFuture.allOf(emailInfo,Attachment).get();
        long end = System.currentTimeMillis();
        System.out.println(hashMap);
        System.out.println(end-start);//861
    }

0 人点赞