一、架构说明

Java中的线程池是通过Exector框架实现的,该框架中用到了Executor,Executors,ExecutorService,ThreadPoolExecutor这几个类。

线程池(二)线程池的3个常用方式_thread
二、编码实现

1、了解即可:

  • Executors.newScheduledThreadPool()
  • java8新出 Executors.newWorkStealingPool(int) 使用目前机器上可用的处理器作为它的并行级别

2、重点掌握

2.1 Executors.newFixedThreadPool(int)

使用场景: 执行长期的任务,性能好很多

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

主要特点如下:
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
使用newFixedThreadPool创建的线程池corePoolSizemaximumPoolSize值是相等的,它使用的是LinkedBlockingQueue

2.2 Executors.newSingleThreadExecutor()

使用场景:一个任务一个任务执行的场景

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

主要特点如下:
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按顺序执行
使用newSignleThreadExecutorcorePoolSizemaxminumPoolSize都设置为1,它使用的是LinkedBlockingQueue;

2.3 Executors.newCachedThreadPool()

使用场景:短期异步的小程序,或者负载较轻的服务器

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

主要特点如下:
创建一个可缓存的线程池,如果线程池长度超过处理需要 ,可灵活回收空闲线程,若无可回收,则新建线程。
使用newCachedThreadPoolcorePoolSize 设置为 0 ,将maximumPoolSize设置为Integer.MAX_VALUE, 使用的SynchronousQueue也就是说来了任务就创建线程运行,当线程空闲超过60s,就自动销毁线程。

3、代码使用案例

package JUC.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadPoolDemo {
    public static void main(String[] args) {
        // 一池5个处理线程
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        //一池1个线程
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        //一池N个线程
//        ExecutorService threadPool = Executors.newCachedThreadPool();

        try {
            for (int i = 0; i < 10000; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t"+"线程进行处理");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }

    }
}