Java中Executors类中几种创建各类型线程池的方法及实例

Executors:提供了一系列静态工厂方法用于创建各种线程池。

1.Executors.newCachedThreadPool创建可变线程池

如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。核心线程池大小为0,最大为Integer.MAX_VALUE,线程空闲存活时间是60秒。

示例代码:

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 1; i <= 5; i++) {
            final int index = i;
            cachedThreadPool.execute(() -> {
                System.out.println(index + "start");
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(index * 1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(index + "end");
        });
}

执行结果:

Executors内部创建newCachedThreadPool源码

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

2.Executors.newFixedThreadPool创建固定大小线程池

核心线程数即为最大线程数,线程不会被回收,直到调用shutdown方法回收

实例代码:

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
	for (int i = 1; i <= 4; i++) {
            final int index = i;
            System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
            fixedThreadPool.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
                    Thread.sleep(1500);
                    System.out.println(Thread.currentThread().getName() + "end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        });
 }

执行结果:


可以看到一直都是两个线程执行。

Executors内部创建newFixedThreadPool源码

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}

3.Executors.newScheduledThreadPool创建定时或周期性任务执行线程池

该线程池可用于定时或周期性任务的执行

定时实例代码:

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
    System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
    //创建线程池后3秒执行
    scheduledThreadPool.schedule(() -> {
        System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
        System.out.println("delay 3 seconds");
}, 3, TimeUnit.SECONDS);

定时执行结果:


周期实例代码:

ScheduledExecutorService scheduleThreadPoolAtFixedRate = Executors.newScheduledThreadPool(5);
System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
//创建线程池后1秒执行 , 之后每3秒执行一次
scheduleThreadPoolAtFixedRate.scheduleAtFixedRate(() -> {
      System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
      System.out.println("delay 1 seconds, and excute every 3 seconds");
}, 1, 3, TimeUnit.SECONDS);

周期执行结果:


Executors内部创建newScheduledThreadPool源码

 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
 }

public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
 }

4.Executors.singleThreadExecutor创建单线的线程池

该线程池有且仅有一个线程执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

实例代码:

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
	for (int i = 1; i <= 4; i++) {
            final int index = i;
            System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
            singleThreadExecutor.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "时间" + System.currentTimeMillis());
                    Thread.sleep(1500);
                    System.out.println(Thread.currentThread().getName() + "end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        });
}

运行结果:


Executors内部创建newSingleThreadExecutor源码

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

4.Executors.newWorkStealingPool创建并行执行线程池

创建一个拥有多个任务队列(以便减少连接数)的线程池

实例代码:

// 设置并行级别为2,即默认每时每刻只有2个线程同时执行
        ExecutorService newWorkStealingPool = Executors.newWorkStealingPool(2);

        for (int i = 1; i <= 4; i++) {
            final int count = i;
            System.out.println("execute" + i);
            newWorkStealingPool.execute(() -> {
                try {
                    Thread.sleep(1000);//此任务耗时1s
                    System.out.println("线程" + Thread.currentThread().getName() + "完成任务:"
                            + count + "   时间为:" + System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

运行结果:


Executors内部创建newWorkStealingPool源码

public static ExecutorService newWorkStealingPool(int parallelism) {
        return new ForkJoinPool
            (parallelism,
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    }

实例代码下载

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值