自定义线程池

自定义线程池

package com.intell.config;
​
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
​
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
​
@Component
public class CustomThreadPool {
​
   //核心线程数
   private final int corePoolSize = 3;
​
   //最大线程数量
   private final int maxPoolSize = 8;
​
   //线程存活时间
   private final int aliveTime = 30;
​
   
   private final ThreadPoolExecutor threadPoolExecutor;
​
   public  CustomThreadPool(){
       this.threadPoolExecutor = create();
  }
​
   public ThreadPoolExecutor create(){
       return new ThreadPoolExecutor(
               corePoolSize,
               maxPoolSize,
               aliveTime,
               TimeUnit.SECONDS,
               new LinkedBlockingQueue<>());
  }
​
   public void start(Runnable runnable){
       threadPoolExecutor.execute(runnable);
  }
​
​
}
​

自定义线程池方便控制线程不造成资源浪费

线程池可自定义拒绝策略,阻塞队列

Thread.sleep(time) 睡眠的是内部线程,当前方法的线程,如果睡眠被打断会抛出异常

posted @ 2023-01-05 09:46  Z_WINTER  阅读(102)  评论(0)    收藏  举报