理解Java - 线程池

Executors创建线程池

Executors提供几种创建线程池的方法:

  1. Executors.newScheduledThreadPool(); //定时任务线程池
  2. Executors.newCachedThreadPool(); //可缓存的线程池
  3. Executors.newSingleThreadExecutor(); //单个线程的线程池
  4. Executors.newFixedThreadPool(); //固定线程数的线程池。

如果使用不当,可能会造成资源耗尽。所以理解内如如何运行很有必要。

看Executors的源码,可以看到Executors创建的线程池都是使用ThreadPoolExecutor。

    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 ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

ThreadPoolExecutor

ThreadPoolExecutor的构造参数有如下几个:

  1. corePoolSize:核心线程数。任务处于空闲时,线程池常驻个数。
  2. maximumPoolSize:最大线程数。当任务处于繁忙时,线程最多能创建个数。
  3. keepAliveTime:线程存活时间。当任务非繁忙时,回收线程数量减少至核心线程数量。
  4. unit: 线程存活时间单位。
  5. workQueue: 阻塞队列
  6. threadFactory: 线程工厂
  7. handler: 拒绝策略
    public ThreadPoolExecutor(int corePoolSize,  //核心线程数
                              int maximumPoolSize, //最大线程数
                              long keepAliveTime,  //线程存活时间
                              TimeUnit unit,    //线程存活时间单位
                              BlockingQueue<Runnable> workQueue, // 阻塞队列
                              ThreadFactory threadFactory,  // 线程工厂
                              RejectedExecutionHandler handler) {  //拒绝策略
                              ......
    }

corePoolSize、maximumPoolSize设置不当会影响效率,甚至耗尽线程;
workQueue设置不当容易导致内存溢出;
handler设置不当会导致提交任务时抛出异常。

使用线程池

        ExecutorService executorService = new ThreadPoolExecutor(2, 5,
                0, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(512), // 避免使用无界队列
                new ThreadPoolExecutor.DiscardPolicy());// 指定拒绝策略
  
        for(int i=0;i<20;i++ ){
            executorService.execute(new ThreadPoolDemo());
        }

在execute方法中,主要处理是通过AddWorker创建、启动线程,和把任务放入阻塞队列。
在这里插入图片描述

Worker

Worker是ThreadPoolExecutor的内部类,它是实现了Runnable接口。
内部持有一个Thread实例,这个实例是线程池中真正运行的线程。
run方法调用runWorker,通过getTask从阻塞队列中取得任务,然后调用任务的run方法。

    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

getTask从阻塞队列中取得任务,如果没有任务会把线程阻塞。核心处理为如下方法:
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);
workQueue.take();

    private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

关于拒绝策略

JDK自带决绝策略有如下几种:

  1. AbortPolicy 抛出RejectedExecutionException(默认的拒绝行为)
  2. DiscardPolicy 什么也不做,直接忽略
  3. DiscardOldestPolicy 丢弃执行队列中最老的任务,尝试为当前提交的任务腾出位置。
  4. CallerRunsPolicy 直接由提交任务者执行这个任务。

自定义拒绝策略:

	// 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理
	private final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
		@Override
		public void rejectedExecution(Runnable r, java.util.concurrent.ThreadPoolExecutor arg1) {
			msgQueue.offer(r); // 把该处理数据暂时缓存起来
		}
	};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值