优雅的创建线程池

手动创建线程

平时开发中经常会碰到需要用异步方式来实现某个需求,这时首先会想到这种写法

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("to do something");
    }
}).start();	

或者用lambda简写

new Thread(()-> System.out.println("to do something")).start();

虽然这种写法可以实现需求,但是我们最好不要这样写,因为这种是不可控的。复杂的系统里,如果有很多这种写法,就会导致明明可以几个线程就能完成的任务,最后创建了几十个线程,导致线程过度切换,降低系统性能。

因此当我们需要异步处理的时候,应该使用线程池

线程池

第一种 使用Executors创建

Executors提供了四种创建线程池的方法

  • newSingleThreadExecutor 创建只有一个线程的线程池,这个线程池可以在线程死后(或发生异常时)重新启动一个线程来替代原来的线程继续执行下去!
public static void main(String[] args) {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.execute(new Worker());
    executorService.execute(new Worker());
    executorService.shutdown();
}
static class Worker implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":working");
    }
}

结果
pool-1-thread-1:working
pool-1-thread-1:working
  • newCachedThreadPool 创建一个可缓存线程池

  • newFixedThreadPool 创建一个定长线程池

  • newScheduledThreadPool 创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。

不推荐使用Executors创建线程池

其实通过Executors创建的四种线程池方法,底层都是通过创建ThreadPoolExecutor来实现的,这四种方法只是为我们封装了创建的细节。但是我们平时开发中最好要知道,核心线程数多少,缓存队列大小等等这些重要的参数,这样以后出现bug不至于无从下手。

第二种 使用ThreadPoolExecutor创建

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}
  • corePoolSize 核心线程数
  • maximumPoolSize 最大线程数
  • keepAliveTime 当线程数大于核心线程数时,空余线程等待新任务的最长时间
  • unit 时间单位
  • workQueue 等待队列
  • threadFactory 线程工厂
  • handler 当线程大于最大线程数时采用的拒绝策略

各个参数如下图所示

threadPool

我们在创建的时候也可以采用ThreadPoolExecutor缺省的构造方法,其中一些参数使用默认即可。

public static void main(String[] args) {
    ThreadFactory threadFactory = new ThreadNameFactory();
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),threadFactory);
    threadPoolExecutor.execute(new Worker());
    threadPoolExecutor.execute(new Worker());
    threadPoolExecutor.shutdown();
}
static class ThreadNameFactory implements ThreadFactory {
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r, threadNumber.getAndIncrement()+"号员工");
    }
}
static class Worker implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":working");
    }
}

结果
1号员工:working
2号员工:working

上面例子中我们设置了核心线程数是5,最大线程数是10,等待时间是5s,等待队列采用的是ArrayBlockingQueue,线程工厂使用自定义的,只是自定义了线程名称。

总结

平时开发中,不论什么时候都最好不要手动创建线程执行异步任务,应该使用线程池来处理,有利于线程可控和复用,提升系统性能,线程池采用ThreadPoolExecutor创建。


扫一扫,关注我

猜你喜欢

转载自blog.csdn.net/weixin_43072970/article/details/106347276