Java多线程系列详解_04_使用jdk预定义线程池创建线程

Executors线程池创建线程代码

/**
 * @author alone
 * @date 2020/12/14 10:20
 * @Description ThreadByExecution
 * 创建线程测试 使用线程池Executors(不推荐)
 */
public class CreateThreadByExecution {

    private static final int FOR_COUNT = 20;

    public static void main(String[] args) throws InterruptedException {
        createExecutionByOne();   // 创建使用单个线程的线程池
        createExecutionStatic();  // 创建使用固定线程数的线程池
        createExecutionCached();    // 创建一个会根据需要创建新线程的线程池
        createExecutionStaticScheduled();    // 创建拥有固定线程数量的定时线程任务的线程池
        createExecutionByOneScheduled();    // 创建只有一个线程的定时线程任务的线程池
    }

    /**
     * 创建只有一个线程的定时线程任务的线程池
     */
    private static void createExecutionByOneScheduled() {
        ScheduledExecutorService es5 = Executors.newSingleThreadScheduledExecutor();
        for (int i = 0; i < FOR_COUNT; i++) {
            es5.schedule(() -> System.out.println(Thread.currentThread().getName() + "正在执行任务!!!"), 3, TimeUnit.SECONDS);
        }
    }

    /**
     * 创建拥有固定线程数量的定时线程任务的线程池
     */
    private static void createExecutionStaticScheduled() {
        //定义线程池大小
        int nThreads = 3;
        ScheduledExecutorService es4 = Executors.newScheduledThreadPool(nThreads);
        for (int i = 0; i < FOR_COUNT; i++) {
            es4.schedule(() -> System.out.println(Thread.currentThread().getName() + "正在执行任务!!!"), 3, TimeUnit.SECONDS);
        }
    }

    /**
     * 创建一个会根据需要创建新线程的线程池
     * 适用场景:快速处理大量耗时较短的任务,如Netty的NIO接受请求时,可使用CachedThreadPool
     */
    private static void createExecutionCached() throws InterruptedException {
        ExecutorService es3 = Executors.newCachedThreadPool();
        for (int i = 0; i < FOR_COUNT; i++) {
//             使用sleep会只创建一个线程
//            Thread.sleep(3000);
            es3.submit(() -> System.out.println(Thread.currentThread().getName() + "正在执行任务"));
        }
    }

    /**
     * 创建使用固定线程数的线程池
     * 适用场景:可用于Web服务瞬时削峰,但需注意长时间持续高峰情况造成的队列阻塞。
     */
    private static void createExecutionStatic() {
        //定义线程池大小
        int nThreads = 3;
        ExecutorService es2 = Executors.newFixedThreadPool(nThreads);
        for (int i = 0; i < FOR_COUNT; i++) {
            es2.submit(() -> System.out.println(Thread.currentThread().getName() + "正在执行任务!!!"));
        }
    }

    /**
     * 创建使用单个线程的线程池 : SingleThreadExecutor被定以后,无法修改,做到了真正的Single。
     */
    private static void createExecutionByOne() {
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        for (int i = 0; i < FOR_COUNT; i++) {
            es1.submit(() -> System.out.println(Thread.currentThread().getName() + "正在执行任务!!!"));
        }
    }
}

Executors创建线程常用介绍

1. Executors.newFixedThreadPool(nThreads):创建使用固定线程数的线程池

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  • corePoolSize与maximumPoolSize相等,即其线程全为核心线程,是一个固定大小的线程池,是其优势;
  • keepAliveTime = 0 该参数默认对核心线程无效,而FixedThreadPool全部为核心线程;
  • workQueue 为LinkedBlockingQueue(无界阻塞队列),队列最大值为Integer.MAX_VALUE。如果任务提交速度持续大余任务处理速度,会造成队列大量阻塞。因为队列很大,很有可能在拒绝策略前,内存溢出。是其劣势;
  • FixedThreadPool的任务执行是无序的;

适用场景:可用于Web服务瞬时削峰,但需注意长时间持续高峰情况造成的队列阻塞。

2. Executors.newCachedThreadPool():创建一个会根据需要创建新线程的线程池

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  • corePoolSize = 0,maximumPoolSize = Integer.MAX_VALUE,即线程数量几乎无限制;
  • keepAliveTime = 60s,线程空闲60s后自动结束。
  • workQueue 为 SynchronousQueue 同步队列,这个队列类似于一个接力棒,入队出队必须同时传递,因为CachedThreadPool线程创建无限制,不会有队列等待,所以使用SynchronousQueue;

适用场景:快速处理大量耗时较短的任务,如Netty的NIO接受请求时,可使用CachedThreadPool。

3. Executors.newSingleThreadExecutor():单例线程,任意时间池中只能有一个线程

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

看的出来像 Executors.newFixedThreadPool(1),但是这里SingleThreadExecutor被包装后,无法成功向下转型。因此,SingleThreadExecutor被定以后,无法修改,做到了真正的Single。

4. Executors.newScheduledThreadPool(nThreads):创建拥有固定线程数量的定时线程任务的线程池

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

newScheduledThreadPool调用的是ScheduledThreadPoolExecutor的构造方法,而ScheduledThreadPoolExecutor继承了ThreadPoolExecutor,构造是还是调用了其父类的构造方法。

5. Executors.newSingleThreadScheduledExecutor():创建只有一个线程的定时线程任务的线程池

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aloneii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值