Springboot 实现线程池 (示例,纯代码)

这里介绍两种:

①注解式:

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import java.util.concurrent.Executor;
 
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
 
    @Override
    public Executor getAsyncExecutor() {
        //线程池设置
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize( 8 );//核心线程
        taskExecutor.setMaxPoolSize( 16 );//最大线程
        taskExecutor.setQueueCapacity( 40 );//队列大小
        taskExecutor.setThreadNamePrefix( "async-service-" );
        taskExecutor.initialize();
        return taskExecutor;
    }
 
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        //直接返回 祖籍 AsyncUncaughtExceptionHandler 对象
        return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
    }
}
@Api(tags = "测试")
@RestController
@RequestMapping("/async")
@Validated
public class AsyncTestController {
    @Autowired
    private AsyncService asyncService;

    @Test
    public void AsyncTest() {
        for (int i = 0; i < 100; i++) {
            this.asyncService.asyncTask1(i);
            this.asyncService.asyncTask2(i);
        }
    }
}
public interface AsyncService {

    void asyncTask1(int i);

    void asyncTask2(int i);
}
/**
 * 直接注解创建线程
 *
 * @author 
 * @Date 2020/6/18
 * @description:
 **/
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {

    /**
     * ①注解式:https://blog.csdn.net/scdncby/article/details/97267865
     *
     * @author 
     * @date 2020/6/18
     * @Param [i]
     **/
    @Override
    @Async
    public void asyncTask1(int i) {
        int q = 1/0;
        log.info("asyncTask1  异步执行  === > 第 {} 次 ", i);
    }

    /**
     * ①注解式:https://blog.csdn.net/scdncby/article/details/97267865
     *
     * @author 
     * @date 2020/6/18
     * @Param [i]
     **/
    @Override
    @Async
    public void asyncTask2(int i) {
        log.info("asyncTask2  异步执行  === > 第 {} 次", i);
    }

}

②配置线程调度管理器

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CustomAsyncScheduler {

    private volatile static CustomAsyncScheduler instance;
    private static ThreadPoolExecutor chnlBackendQueryPool;

    private CustomAsyncScheduler () { }

    @SuppressWarnings( {"rawtypes","static-access","unchecked"} )
    public static CustomAsyncScheduler getInstance() {
        if (instance == null){
            synchronized (CustomAsyncScheduler.class){
                if (instance == null ) {
                    instance = new CustomAsyncScheduler();
                    BlockingQueue queue = new LinkedBlockingQueue();
                    chnlBackendQueryPool = new ThreadPoolExecutor( 50, 100, 30, TimeUnit.SECONDS, queue );
                    chnlBackendQueryPool.allowCoreThreadTimeOut( true );
                    setChnlBackendQueryPool( chnlBackendQueryPool );
                }
            }
        }
        return instance;
    }

    public ThreadPoolExecutor getChnlBackendQueryPool() {
        return chnlBackendQueryPool;
    }

    public static void setChnlBackendQueryPool(ThreadPoolExecutor chnlBackendQueryPool) {
        CustomAsyncScheduler.chnlBackendQueryPool = chnlBackendQueryPool;
    }

    public static void setInstance(CustomAsyncScheduler instance) {
        CustomAsyncScheduler.instance = instance;
    }
}
@Api(tags = "测试")
@RestController
@RequestMapping("/async")
public class AsyncTestController {
    @Autowired
    private AsyncService asyncService;

    @Test
    public void AsyncTest() {
        for (int i = 0; i < 100; i++) {
            this.asyncService.executeAsuncTask3(i);
            this.asyncService.executeAsuncTask4(i);
        }
    }
}
public interface AsyncService {

   void executeAsuncTask3(int i);

   void executeAsuncTask4(int i);
}
mport com.dell.threadpool.config.CustomAsyncScheduler;
import com.dell.threadpool.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 直接注解创建线程
 *
 * @author xuemd
 * @Date 2020/6/18
 * @description:
 **/
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {
    /**
     * ②配置线程调度管理器:https://blog.csdn.net/scdncby/article/details/97267865
     *
     * @author xuemd
     * @date 2020/6/18
     * @Param [i]
     **/
    @Override

    public void executeAsuncTask3(int i) {
        CustomAsyncScheduler.getInstance().getChnlBackendQueryPool().execute(new Runnable() {
            @Override
            public void run() {
                log.info("asyncTask3  异步执行  === > 第 {} 次", i);

            }
        });
    }

    /**
     * ②配置线程调度管理器:https://blog.csdn.net/scdncby/article/details/97267865
     *
     * @author xuemd
     * @date 2020/6/18
     * @Param [i]
     **/
    @Override
    public void executeAsuncTask4(int i) {
        CustomAsyncScheduler.getInstance().getChnlBackendQueryPool().execute(new Runnable() {
            @Override
            public void run() {
                log.info("asyncTask4  异步执行  === > 第 {} 次", i);

            }
        });
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值