线程池的基本使用

2020-10-20  本文已影响0人  笑疯子

线程池作用

借由《Java并发编程的艺术》

ThreadPoolExecutor类

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    ...
}

ThreadPoolExecutor构造

ThreadPoolExecutor类的构造参数:

常用的拒绝策略

ThreadPoolExecutor线程状态

创建线程池

创建Runnable接口实现类

public class MyThread implements Runnable {

    private String taskName;

    public MyThread(String taskName) {
        this.taskName = taskName;
    }

    @Override
    public void run() {
        try {
            String threadName = Thread.currentThread().getName();
            System.out.println("线程 " + threadName + " 开始执行:" + taskName);
            Thread.sleep(3000);
            System.out.println("线程 " + threadName + " 开始执行:" + taskName);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "MyThread{" +
                "taskName='" + taskName + '\'' +
                '}';
    }
}

使用ThreadPoolExecutor创建

public static void main(String[] args) {

    ThreadPoolExecutor executor = new ThreadPoolExecutor(
            // 核心线程数
            5,
            // 最大线程数
            10,
            // 等待时间
            100,
            // 等待时间单位  秒
            TimeUnit.SECONDS,
            // 任务队列 容量100
            new ArrayBlockingQueue<>(100),
            // 饱和策略
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    for (int i = 1; i <= 10; i++) {
        MyThread myThread = new MyThread("任务" + i);
        executor.execute(myThread);
    }

    executor.shutdown();
}

几种常见的线程池

固定线程池(FixThreadPool)

线程池中的固定数量线程可以重复使用

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

创建方法:

ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 1; i <= 10; i++) {
    MyThread myThread = new MyThread("任务" + i);
    executor.execute(myThread);
}

需要注意的是,LinkedBlockingQueue是一个无界队列,它的容量为:Integer.MAX_VALUE,也就是说,当所有线程被占用后,新的任务将会无限堆加到这个队列中,如果任务较多,可能会出现OOM现象。

单一线程池(SingleThreadExecutor)

只有一个线程,空闲也不会被关闭。

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

创建方法:

ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 1; i <= 10; i++) {
    MyThread myThread = new MyThread("任务" + i);
    executor.execute(myThread);
}

缓存线程池(CachedThreadPool)

线程数量为Integer.MAX_VALUE,空闲线程会被临时缓存60s,没有任务分配会关闭。如果提交任务速度过快,也一样可能会出现OOM现象。

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

创建方法:

ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 1; i <= 10; i++) {
    MyThread myThread = new MyThread("任务" + i);
    executor.execute(myThread);
}

原文发布在:传送门

上一篇下一篇

猜你喜欢

热点阅读