ThreadPoolExecutor 使用

ThreadPoolExecutor 使用

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { }

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { }

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { }

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

这是线程池的四个构造方法

使用场景:用于负载比较重的服务器,为了资源的合理利用,需要限制当前线程数量。

corePoolSize: 核心线程的数量,当线程池的线程超过或者等于这个数量时,新的线程任务会放到workQueue任务队列中。

maximumPoolSize: 线程的最大数量,当线程池的线程超过或者等于这个数量时,新的线程任务会放到workQueue任务队列中,如果任务队列满了,会创建新的线程执行任务,但线程总数始终不会超过maximumPoolSize,如果创建新任务时,任务队列满了,而且线程数量已经达到maximumPoolSize,处理方式会由 handler 参数决定。

keepAliveTime:静止(不在工作状态)线程的失效时间,默认只会失效非核心线程,但调用threadPoolExecutor.allowCoreThreadTimeOut(true)方法后会失效所有线程

unit:keepAliveTime参数的时间单位

workQueue:任务队列,常用的有 ArrayBlockingQueue,LinkedBlockingQueue,SynchronousQueue
ArrayBlockingQueue先进先出,初始化时需要指定长度,LinkedBlockingQueue先进先出,默认长度为Integer.MAX_VALUE也可以指定长度,SynchronousQueue比较特殊,不会储存任务,而是直接创建一个线程执行任务

threadFactory:用于创建线程任务,传入的线程任务会经过threadFactory的newThread方法预处理

handler:任务拒绝方式,
new ThreadPoolExecutor.AbortPolicy() 丢弃任务抛出RejectedExecutionException
new ThreadPoolExecutor.DiscardOldestPolicy() 丢弃最前边任务,尝试执行新任务
new ThreadPoolExecutor.DiscardPolicy() 丢弃任务
new ThreadPoolExecutor.CallerRunsPolicy() 由调用线程处理任务

示例代码

public class ThreadPoolTest {

	public static void main(String[] args) {

		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(5),new ThreadPoolExecutor.DiscardPolicy());

		for (int i = 0; i <= 20; i++) {
			StringBuffer str = new StringBuffer("");
			str.append(i);
			threadPoolExecutor.execute(() -> {
				System.out.println(str);
			});
		}

		threadPoolExecutor.shutdown();
	}
}

以上代码如果没有 new ThreadPoolExecutor.DiscardPolicy() 这个参数会引 RejectedExecutionException,且shutdown方法不能正常结束

List<Runnable> runnables = threadPoolExecutor.shutdownNow(); //立即终止线程池,打断正在执行的任务,但会未完成的任务

threadPoolExecutor.shutdown();//拒绝接收新的任务,等任务执行完毕,终止线程池

//有返回结果的执行任务
Future<String> result = threadPoolExecutor.submit(()->{
			
			return "Hello Word!";
		});

也可以使用Executors的静态房方法构建线程池

发布了43 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43866295/article/details/88847486