技术复习-java线程池

ThreadPoolExecutor

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

参数详解

  1. corePoolSize 核心线程数 当线程数<corePoolSize时,新建线程。java

  2. maxinumPoolSize 最大线程数线程

  3. keepAliveTime 存活时间 当线程数>corePoolSize时,空闲线程存活的最长时间code

  4. timeUnit 单位时间继承

  5. workQueue 保存任务的阻塞队列队列

  6. threadFactory 线程建立工厂get

  7. handler 拒绝策略it

任务执行顺序

  1. 当线程数<corePoolSize时,新建线程执行任务。
  2. 当线程数>corePoolSize,且workQueue未满的时候,任务加到workQueue中。
  3. 当线程数>corePoolSize,且workQueue满了,且当前线程数<maximumPoolSize,则新起线程执行。
  4. 当线程数>corePoolSize,且workQueue满了,且当前线程数>=maximumPoolSize,则执行拒绝策略

4个默认拒绝策略

拒绝策略默认有4种 1.抛出异常 2.直接丢弃 3.丢弃队列中最老的 4.直接调用run方法,阻塞执行。 固然也能够继承RejectedExecutionHandler实现本身的拒绝策略io

Executors

由于参数比较多,java中的Exectors提供了简便的线程池建立方式。thread

1.Executors#newFixedThreadPool(int nThreads) 固定线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
		return new ThreadPoolExecutor(nThreads, nThreads,
			 0L, TimeUnit.MILLISECONDS,
			 new LinkedBlockingQueue<Runnable>());
	}

能够看到用的workQueue是LinkedBlockingQueue,说明队列无限长,线程池最大值就是入参nThreads。线程池

2.Executors#newCachedThreadPool() 线程池为Integer.MAX_VALUE的线程池
public static ExecutorService newCachedThreadPool() {
		return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
		60L, TimeUnit.SECONDS,
		new SynchronousQueue<Runnable>());
	}

SynchronousQueue是容量为1的阻塞队列,因此新增任务的时候会新起线程,线程数最大值为Integer.MAX_VALUE

3.Executors#newSingleThreadPool() 线程数为1的线程池
public static ExecutorService newSingleThreadExecutor() {
		return new FinalizableDelegatedExecutorService
			(new ThreadPoolExecutor(1, 1,
			0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>()));
	}

不用说了,线程数最大为1。

TaskFuture

继承于Future,可以实现带返回值的线程执行结果。 几个特殊方法, isDone() get(),get(Long timeOut,TimeUtil) cancel(),isCancel()

相关文章
相关标签/搜索