Executor实现类--ThreadPoolExecutor

本文详细介绍了Java中的ThreadPoolExecutor类,包括其构造参数的作用及如何通过示例代码来配置和使用线程池。同时探讨了不同级别的程序员对于并发编程难度的看法。

• Junior programmers think concurrency is hard.
• Experienced programmers think concurrency is easy.
• Senior programmers think concurrency is hard.

初级程序员认为并发编程很难;

有经验的程序员认为并发编程很容易;

高级程序员认为并发编程很难。

不知道是不是这么一回事,反正对我来说难。


今天记录一个Executor的实现类ThreadPoolExecutor的实例。


ThreadPoolExecutor 保持一个线程池并且分发Runnable的实例到线程池中的execute()方法执行。

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

corePoolSize: 决定初始时线程池有多少个线程被启动,当队列满时才会启动新的线程。

maximumPoolSize: 线程池中启动的最大的线程数量,可以设置Integer.MAX_VALUE 让线程池的线程数量没有上限。

keepAliveTime: 当ThreadPoolExecutor实例创建超过corePoolSize数量的线程时,一个线程空闲多少时间后将被从线程池中移除。

unit: keepAliveTime的时间单位。

workQueue: 保持在execute()方法执行的Runnable实例的队列,到这个Runnable实例被启动。

threadFactory: 创建用于ThreadPoolExecutor的线程的接口的工厂实现类。

handler: 当你指定一个工作缓冲队列和一个线程池最大线程数量,有可能出现ThreadPoolExecutor实例因为饱和而无法处理的一些Runnable实例。在这种情况下,会调用提供的handler实例,使你能在发生这种情况时做一些处理。


ThreadPoolExecutorExample:

package club.younge.demo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorExample implements Runnable {//本类为线程实现类
	private static AtomicInteger counter = new AtomicInteger();
	private final int taskId;

	public int getTaskId() {
		return taskId;
	}

	public ThreadPoolExecutorExample(int taskId) {
		this.taskId = taskId;
	}

	public void run() { //线程真正执行
		try {
			System.out.println("executor work thread " + taskId );
			Thread.sleep(5000);    //休眠5秒
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(10);  //工作缓存队列
		ThreadFactory threadFactory = new ThreadFactory() {    //线程制造工厂,
			public Thread newThread(Runnable r) { //线程创建
				int currentCount = counter.getAndIncrement();
				System.out.println("Creating new thread: " + currentCount);
				return new Thread(r, "mythread" + currentCount);
			}
		};
		RejectedExecutionHandler rejectedHandler = new RejectedExecutionHandler() { //被拒的Runnable处理Handler
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				if (r instanceof ThreadPoolExecutorExample) {
					ThreadPoolExecutorExample example = (ThreadPoolExecutorExample) r;
					System.out.println("Rejecting task with id " + example.getTaskId());
				}
			}
		};
		ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS, queue, threadFactory, rejectedHandler);
		for (int i = 0; i < 100; i++) {
			executor.execute(new ThreadPoolExecutorExample(i));
		}
		executor.shutdown();
                //executor.shutdownNow();//正在休眠的10线程将被立即唤醒,跳入InterruptedException异常,并打印堆栈信息。
	}
}


ThreadPoolExecutor 是 Java 中用于线程池管理的一个核心类,它允许你在程序中创建一组工作线程,以便管理和调度执行任务。它的基本构造包括以下几个关键部分: 1. 工作线程数(corePoolSize):这是线程池默认启动的线程数量,它们始终在线运行。 2. 最大线程数(maximumPoolSize):当任务提交的速度超过核心线程处理能力时,线程池会自动增加额外的工作线程,直到达到这个最大值。 3. 阻塞队列(workQueue):用于存储等待执行的任务。如果所有线程都在忙,新任务将进入阻塞队列。 4. 空闲线程策略(keepAliveTime):当工作队列为空且所有核心线程都处于活动状态时,多余的非核心线程会在指定时间内等待新任务的到来,否则会被终止。 5. 守护线程(allowCoreThreadTimeOut):设置为 true 时,主线程退出时会尝试停止所有核心线程。 6. 提交任务的拒绝策略(handler):当工作队列已满且无法接受新任务时,可以配置不同的策略如直接丢弃、循环等待等。 通过 ThreadPoolExecutor,你可以有效地控制并发任务的数量,避免资源耗尽,并且实现任务的异步执行。例如,创建一个线程池并提交任务的代码可能会像下面这样: ```java int corePoolSize = 5; int maxPoolSize = 10; long keepAliveTime = 60; // 单位为秒 ThreadPoolExecutor executor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy() ); executor.execute(yourRunnableTask); // 提交任务 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值