线程池的创建和使用,不建议直接使用Executor创建

实现线程池,有四种策略:

生成线程池采用了工具类Executors的静态方法,以下是四种常见的线程池。

SingleThreadExecutor:单个后台线程 (其缓冲队列是无界的)。

创建一个单线程的线程池。这个线程池只有一个核心线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。

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

FixedThreadPool:只有核心线程的线程池,大小固定 (其缓冲队列是无界的) 。

创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。

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

CachedThreadPool:无界线程池,可以进行自动线程回收。

如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。SynchronousQueue是一个是缓冲区为1的阻塞队列。 

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

ScheduledThreadPool:核心线程池固定,大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

创建一个周期性执行任务的线程池。如果闲置,非核心线程池会在DEFAULT_KEEPALIVEMILLIS时间内回收。

   public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    public ScheduledThreadPoolExecutor( int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
              new DelayedWorkQueue());
    }

提交任务方式

ExecutorService.execute(Runnable runable);

FutureTask task = ExecutorService.submit(Runnable runnable);

FutureTask<T> task = ExecutorService.submit(Runnable runnable,T Result);

FutureTask<T> task = ExecutorService.submit(Callable<T> callable);

package com.xyz.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class ExecutorsDemo {
	
	private final static Logger logger=LoggerFactory.getLogger(ExecutorsDemo.class);
	
	private static ThreadFactory nameThreadFactory=new ThreadFactoryBuilder()
			.setNameFormat("demo-pool-%d").build();

	/**
	 * corePoolSize - 池中所保存的线程数,包括空闲线程。
	 * maximumPoolSize-池中允许的最大线程数。
	 * keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。
	 * unit - keepAliveTime 参数的时间单位。
	 * workQueue - 执行前用于保持任务的队列。此队列仅保持由 execute方法提交的 Runnable任务。
	 * threadFactory - 执行程序创建新线程时使用的工厂。
	 * handler - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。
	 */
	private static ExecutorService pool=new ThreadPoolExecutor(5, 10, 0L, 
			TimeUnit.MILLISECONDS, 
			new LinkedBlockingQueue<Runnable>(1024), nameThreadFactory,
new ThreadPoolExecutor.AbortPolicy());
	public static void main(String[] args) {
		
		for(int i=0;i<Integer.MAX_VALUE;i++) {
			pool.execute(new Thread() {

				@Override
				public void run() {
					logger.info(Thread.currentThread().getName());
				}
				
			});
		}
	}
}

Executors 返回线程池对象的弊端如下:
FixedThreadPool 和 SingleThreadExecutor : 允许请求的队列长度为 Integer.MAX_VALUE,可能堆积大量的请求,从而导致OOM。
CachedThreadPool 和 ScheduledThreadPool : 允许创建的线程数量为 Integer.MAX_VALUE ,可能会创建大量线程,从而导致OOM。

猜你喜欢

转载自blog.csdn.net/jellyjiao2008/article/details/82899027
今日推荐