java使用多线程

import java.util.concurrent.TimeUnit;
import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadFactoryBuilder;

//构造多线程,可修改线程数
ExecutorService executorService = ExecutorBuilder.create()
        .setCorePoolSize(5) // 初始线程数
        .setMaxPoolSize(10) // 最大线程数
        .setThreadFactory(ThreadFactoryBuilder.create().setNamePrefix("dapData_").build()) // 设置线程名称前缀
        .setWorkQueue(new LinkedBlockingQueue<>(100)) // 有界等待队列,最大等待数是100
        .build();

// 使用多线程
// 方法1
for(){
    executorService.execute(new Runnable() {
        @Override
        public void run(){
            //执行操作
        }
    });
}

// 方法2
for(){
    executorService.submit(() -> {
        //执行操作
    });
}

// 方法3
//如果不方便使用for循环,直接多写几个executorService.execute()也是一样的。

//关闭多线程
executorService.shutdown();
try {
    boolean success = executorService.awaitTermination(10, TimeUnit.MINUTES);
    if (!success) {
        log.error("线程池关闭失败");
    }
} catch (InterruptedException e) {
    log.error("线程池关闭失败",e);
}

posted @ 2024-09-12 12:29  chenzechao  阅读(25)  评论(0)    收藏  举报