ThreadPoolExecutor 介绍

ThreadPoolExecutor 类用来创建自定义的线程池。

使用示例

class RunnableThread implements Runnable {
    @Override
    public void run() {
        System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName() + " ");
    }
}

public class Test {
    public static void main(String[] args) throws Exception{
        ExecutorService executorService = new ThreadPoolExecutor(
                2, //核心线程数
                Runtime.getRuntime().availableProcessors(), //最大线程数,cpu 核数
                3, //超时时间
                TimeUnit.SECONDS, //超时单位
                new LinkedBlockingDeque<>(3), //等待队列
                Executors.defaultThreadFactory(), //线程工厂
                new ThreadPoolExecutor.AbortPolicy()); //拒绝策略

        for(int i = 0; i<8; i++) {
            RunnableThread thread = new RunnableThread();
            executorService.execute(thread);
        }
        //关闭线程池
        executorService.shutdown();
    }
}

结果:
通过线程池方式创建的线程:pool-1-thread-1 
通过线程池方式创建的线程:pool-1-thread-4 
通过线程池方式创建的线程:pool-1-thread-3 
通过线程池方式创建的线程:pool-1-thread-2 
通过线程池方式创建的线程:pool-1-thread-4 
通过线程池方式创建的线程:pool-1-thread-3 
通过线程池方式创建的线程:pool-1-thread-5 
通过线程池方式创建的线程:pool-1-thread-2 

相关文章:

  • 2021-09-06
  • 2021-06-05
  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
  • 2022-02-19
  • 2021-10-25
猜你喜欢
  • 2022-01-24
  • 2018-03-11
  • 2018-12-09
相关资源
相似解决方案