经典简单的线程池操作

DBC 326 0

经典简单的线程池操作

1、带线程等待

经典定义线程池

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 功能描述 : 线程池配置
 *
 * @author :  dbc
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor simpleThreadPool() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("siccs-pool-%d").build();
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        threadPoolTaskExecutor.setThreadFactory(threadFactory);
        threadPoolTaskExecutor.setCorePoolSize(32);
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        threadPoolTaskExecutor.setMaxPoolSize(64);
        threadPoolTaskExecutor.setQueueCapacity(80);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
    
}

开线程小例子

    @Autowired
    ThreadPoolTaskExecutor myThreadPoolTaskExecutor;

经典简单的线程池操作插图

可以看看代码

        // 线程池跑sql 大sql拆分小sql  避免大sql的压力  strat
        CompletableFuture<Void> Future1 = CompletableFuture.runAsync(() -> {
            // 你的方法
        }, myThreadPoolTaskExecutor);

        // test
        CompletableFuture<Void> Future2 = CompletableFuture.runAsync(() -> {
            // 你的方法
        }, myThreadPoolTaskExecutor);

        CompletableFuture<Void> Future3 = CompletableFuture.runAsync(() -> {
            // 你的方法
        }, myThreadPoolTaskExecutor);

        // 等待所有线程执行结束
        CompletableFuture.allOf(Future1, Future2, Future3).get();
        // 线程池跑sql 大sql拆分小sql  避免大sql的压力  end

发表评论 取消回复
表情 图片 链接 代码

分享