原创

JUC中Executors工具类使用创建线程池、线程工厂、Runnable转Callable等

创建ThreadPoolExecutor线程池

newSingleThreadExecutor: 单线程池

只有一个线程的线程池,只用一个线程来执行任务,保证任务按FIFO( First Input First Output,简单说就是指先进先出)顺序一个个执行,保证执行顺序。使用无限队列可能会导致OOM。

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

newFixedThreadPool:固定线程数的线程池

只能创建核心线程的线程池,使用无限队列可能会导致OOM。

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

newCachedThreadPool:可缓存的线程池

没有核心线程,只有非核心线程在执行任务,可创建的最大线程数为int最大值,使用的是同步单一阻塞队列。

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

newScheduledThreadPool:固定线程数,支持定时、周期性执行任务的线程池

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

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

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

使用示例:

private static void newScheduledThreadPool() {
    ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
    // 延时3秒执行
    service.schedule( () -> {
        System.out.println(3);
    }, 3, TimeUnit.SECONDS);

    // 1秒后每3秒循环执行
    service.scheduleAtFixedRate( () -> {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(4);
    }, 1, 3, TimeUnit.SECONDS);

    // 1秒后每当线程执行完之后3秒循环执行
    service.scheduleWithFixedDelay( () -> {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(5);
    }, 1, 3, TimeUnit.SECONDS);

//        service.shutdown();
}

创建ForkJoinPool线程池

newWorkStealingPool 并行协作线程池

任务会分割为几个自任务,执行完成之后还会帮助其他线程去执行任务,详情看ForkJoinPool线程池。

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

public static ExecutorService newWorkStealingPool() {
    // Runtime.getRuntime().availableProcessors():返回可用于Java虚拟机的处理器数量。
    return new ForkJoinPool
        (Runtime.getRuntime().availableProcessors(),
         ForkJoinPool.defaultForkJoinWorkerThreadFactory,
         null, true);
}

使用juc工具类创建线程工厂

public static ThreadFactory defaultThreadFactory() {
    return new DefaultThreadFactory();
}

public static ThreadFactory privilegedThreadFactory() {
    return new PrivilegedThreadFactory();
}

将Runnable转换成Callable

public static <T> Callable<T> callable(Runnable task, T result) {
    if (task == null)
        throw new NullPointerException();
    return new RunnableAdapter<T>(task, result);
}
正文到此结束
本文目录