Java多线程—线程池

1、什么是线程池,为什么使用

线程池由任务队列和工作线程组成,因线程的创建和销毁比较耗资源,为了提高效率引入线程池,正确使用线程池可以

降低资源消耗,重用已经存在的线程

更好管理线程,控制最大最优的线程并行数量,提高响应效率

提供定时,延迟执行,单线程FIFO执行


2、线程相关类,方法,源码

ExecutorService,ScheduledExecutorService接口

位于java.util.concurrent包中,继承Excutor,提供了操作线程池的重要方法,如执行任务execute(),submit()和停止任务shutdown(),shutdownNow()等

ThreadPoolExecutor类

线程池本身属性,线程池内线程维护,任务队列任务调度管理

核心属性

corePoolSize:线程池中核心线程数,当任务队列中有待执行的任务时,线程池就创建一个新线程执行任务,即使池内还有空闲的线程,直到池中线程数等于corePoolSize,之后再有任务提交到阻塞队列中,会等待,prestartAllCoreThreads()方法可使线程池提前创建并启动核心线程数的线程

maximumPoolSize:线程池维护的最大线程数,当池内的线程数量等于corePoolSize且都没有空闲,任务队列也已经满了,此时会创建新的线程来执行任务,直到线程数等于maximumPoolSize

keepAliveTime:线程在空闲时存活时间,一般线程数大于corePoolSize时起作用

unit:keepAliveTime时间单位

workQueue:用来保存被执行的任务的阻塞队列,保存的任务需要实现Runnable接口

threadFactory:创建线程工厂,自定义创建线程方式,如设置线程名等

handler:线程池饱和策略,当线池内corePoolSize已满,阻塞队列也已经排满任务时,并且创建了maximumPoolSize数的线程,此时还有新任务提交时的一种处理策略。

构造方法

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler ) {

    if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0)

        throw new IllegalArgumentException();

    if (workQueue == null || threadFactory == null || handler == null)

        throw new NullPointerException();

    this.acc = System.getSecurityManager == null ? null : AccessController.getContext();

    this.corePoolSize = corePoolSize;

    this.maximumPoolSize = maximumPoolSize;

    this.workQueue = workQueue;

    this.keepAliveTime = unit.toNanos(keepAliveTime);

    …

}

Executors类

工厂类,主要给外部提供创建线程池方法     

…、FixedThreadPool固定线程数的线程池,corePoolSize=maximumPoolSize

public static ExecutorService newFixedThreadPool(int nThreads) {

    return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());

}

…、cachedThreadPool可缓存线程的线程池,默认不限制最大线程数,默认空闲时间为60秒,当线程空闲时间超过60秒则释放,当新任务来时没有空闲线程则创建

public static ExecutorService newCachedThreadPool(){

    return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue());

}

…、singleThreadScheduledExecutor,单线程线程池,池内只存在一个线程,如果线程异常了会创建新的线程

public static ExecutorService newSingleThreadExecutor() {

    return new FinalizableDelegatedExecutorService( new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()));

}

…、scheduledThreadPool,指定时间后周期性执行任务

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {

    return new SchedledThreadPoolExecutor(corePoolSize);

}

public ScheduledThreadPoolExecutor(int corePoolSize) {

    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());

}


3、主要方法区别

…:execute() 和 submit()

2个方法都是用来执行任务使用

void execute(Runnable command);

Future submit(Runnable task);

对于不需要返回值的直接用executor,submit返回一个Future用于包装返回值,底层实际还是调用execute

…:shutdown() 和 shutdownNow()

2个方法都是用来关闭线程池的

void shutdown();

List shutdownNow();

shutdown(),关闭线程池,并释放线程池内空闲的线程,对已经提交的任务还是会执行完

shutdownNow() 关闭线程池,停止所有正在执行的任务,释放线程。会将中断的任务放到List中返回


4、使用案例

class TestRunnable implements Runnable {

    public void run() {…}

}

public class Test {

    public static void main(String[], args) {

        TestRunnable runnable = new TestRunnable();


        ExecutorService fixedPool = Executors.newFixedThreadPool(5);

        for(int i = 0; i < 10; i++) {

            fixedPool.execute(runnable);

        }


        ExecutorService cachedPool = Executors.newCachedThreadPool();


        ScheduledExecutorService scheduledPool = Executors.newScheduleThreadPool(5);

        // 10秒后开始执行

        scheduledPool.schedule(runnable, 10, TimeUnit.SECONDS);

        // 10秒后开始执行第一遍,之后每隔5秒再次执行

        scheduledPool.scheduleAtFixedRate(runnable, 10, 5, TimeUnit.SECONDS);


        ExecutorService singlePool = Executor.newSingleThreadExecutor();

        singlePool.execute();

    }

}

你可能感兴趣的:(Java多线程—线程池)