线程池

先写一个线程池的配置类

package com.bxr.cs.threadpool;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

//启动异步
@EnableAsync
//这是一个配置类
@Configuration
class TaskPoolConfig {
    //设置Bean的名称不设置的话没有办法在 任务中对应 配置信息
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        //根据ThreadPoolTaskExecutor 创建建线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //为线程设置初始的线程数量 5条线程
        executor.setCorePoolSize(5);
        //为线程设置最大的线程数量 10条线程
        executor.setMaxPoolSize(10);
        //为任务队列设置最大 任务数量
        executor.setQueueCapacity(200);
        //设置 超出初始化线程的 存在时间为60秒
        //也就是 如果现有线程数超过5 则会对超出的空闲线程 设置摧毁时间 也就是60秒
        executor.setKeepAliveSeconds(60);
        //设置 线程前缀
        executor.setThreadNamePrefix("taskExecutor-");
        //线程池的饱和策略 我这里设置的是 CallerRunsPolicy 也就是由用调用者所在的线程来执行任务 共有四种
        //AbortPolicy:直接抛出异常,这是默认策略;
        //CallerRunsPolicy:用调用者所在的线程来执行任务;
        //DiscardOldestPolicy:丢弃阻塞队列中靠最前的任务,并执行当前任务;
        //DiscardPolicy:直接丢弃任务;
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //设置在关闭线程池时是否等待任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置等待终止的秒数
        executor.setAwaitTerminationSeconds(60);
        //返回设置完成的线程池
        return executor;
    }
}

再写一个使用线程池的类


package com.bxr.cs.threadpool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class test {
    //异步使用配置类 Bean名为 taskExecutor
    @Async("taskExecutor")
    public void Hello(String hello) throws InterruptedException {
        log.info("任务开始并延长执行时间");
        Thread.sleep(1000);
        log.info(hello);
    }
}

模拟其余方法调用该使用线程池的类

package com.bxr.cs.threadpool;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    private test test;

    @Test
    public void test() throws Exception {

        for (int i = 0;i<30;i++){
            test.Hello("test"+i);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容