Java 线程池 从入门到深入

2021-11-18  本文已影响0人  Java技术分享45

类图

该类图也是从左到右按入门到深入绘制的。

Java 线程池.png

入门

创建线程池实例

使用java.util.concurrent.Executors工具类创建线程池。
Executors工具类提供如下静态方法来创建多种类型的线程池实例:

public static ExecutorService newSingleThreadExecutor()
public static ExecutorService newFixedThreadPool(int nThreads) 
public static ExecutorService newCachedThreadPool() 
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
public static ScheduledExecutorService newSingleThreadScheduledExecutor()
public static ExecutorService newWorkStealingPool()

Executors抽象的常用的线程池类型

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
public static ExecutorService newWorkStealingPool() {
        return new ForkJoinPool
            (Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    }

通过线程池运行线程

可以提交单个、多个线程。

提交单个线程

提交多个线程

停止线程池

线程池结束状态

Executors创建线程池不足

是否真的存在阿里巴巴Java开发手册中存在的问题有待考量。

上一篇 下一篇

猜你喜欢

热点阅读