一、模拟实现线程池
1.1 基础线程池实现
java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* 简易线程池实现
*/
public class MyThreadPool {
private final BlockingQueue<Runnable> taskQueue;
private final Thread[] workerThreads;
private volatile boolean isShutdown = false;
public MyThreadPool(int corePoolSize) {
this.taskQueue = new ArrayBlockingQueue<>(corePoolSize * 2);
this.workerThreads = new Thread[corePoolSize];
// 初始化工作线程
for (int i = 0; i < corePoolSize; i++) {
workerThreads[i] = new Worker("Pool-Thread-" + i);
workerThreads[i].setDaemon(true); // 设置为守护线程
workerThreads[i].start();
}
}
/**
* 提交任务到线程池
*/
public void submit(Runnable task) throws InterruptedException {
if (isShutdown) {
throw new IllegalStateException("ThreadPool is shutdown");
}
taskQueue.put(task);
}
/**
* 优雅关闭线程池
*/
public void shutdown() {
isShutdown = true;
for (Thread worker : workerThreads) {
worker.interrupt();
}
}
/**
* 立即关闭线程池
*/
public void shutdownNow() {
isShutdown = true;
for (Thread worker : workerThreads) {
worker.interrupt();
}
taskQueue.clear();
}
/**
* 工作线程类
*/
private class Worker extends Thread {
public Worker(String name) {
super(name);
}
@Override
public void run() {
while (!isShutdown && !Thread.currentThread().isInterrupted()) {
try {
// 从队列中获取任务,支持超时以便响应关闭信号
Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS);
if (task != null) {
task.run();
}
} catch (InterruptedException e) {
// 响应中断,退出线程
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
// 捕获任务执行异常,避免工作线程退出
System.err.println("Task execution failed: " + e.getMessage());
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " is terminated");
}
}
}
1.2 增强版线程池(支持拒绝策略)
java
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 增强版线程池,支持拒绝策略和线程工厂
*/
public class EnhancedThreadPool {
private final BlockingQueue<Runnable> taskQueue;
private final Thread[] workerThreads;
private volatile boolean isShutdown = false;
private final RejectedExecutionHandler rejectedHandler;
private final ThreadFactory threadFactory;
private final AtomicInteger completedTasks = new AtomicInteger(0);
// 拒绝策略枚举
public enum RejectPolicy {
ABORT, // 抛出异常
DISCARD, // 静默丢弃
DISCARD_OLDEST,// 丢弃队列中最老的任务
CALLER_RUNS // 由调用者线程执行
}
public EnhancedThreadPool(int corePoolSize, int queueCapacity,
RejectPolicy policy, ThreadFactory factory) {
this.taskQueue = new ArrayBlockingQueue<>(queueCapacity);
this.workerThreads = new Thread[corePoolSize];
this.rejectedHandler = createRejectedHandler(policy);
this.threadFactory = factory != null ? factory : new DefaultThreadFactory();
initializeWorkers();
}
private void initializeWorkers() {
for (int i = 0; i < workerThreads.length; i++) {
workerThreads[i] = threadFactory.newThread(new Worker());
workerThreads[i].start();
}
}
/**
* 提交任务
*/
public void execute(Runnable task) {
if (isShutdown) {
rejectedHandler.rejectedExecution(task, this);
return;
}
if (!taskQueue.offer(task)) {
rejectedHandler.rejectedExecution(task, this);
}
}
/**
* 获取已完成任务数
*/
public int getCompletedTaskCount() {
return completedTasks.get();
}
/**
* 获取队列大小
*/
public int getQueueSize() {
return taskQueue.size();
}
/**
* 创建拒绝策略处理器
*/
private RejectedExecutionHandler createRejectedHandler(RejectPolicy policy) {
switch (policy) {
case ABORT:
return new ThreadPoolExecutor.AbortPolicy();
case DISCARD:
return new ThreadPoolExecutor.DiscardPolicy();
case DISCARD_OLDEST:
return new ThreadPoolExecutor.DiscardOldestPolicy();
case CALLER_RUNS:
return new ThreadPoolExecutor.CallerRunsPolicy();
default:
return new ThreadPoolExecutor.AbortPolicy();
}
}
/**
* 默认线程工厂
*/
private static class DefaultThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "EnhancedPool-Thread-" + threadNumber.getAndIncrement());
t.setDaemon(true);
return t;
}
}
/**
* 工作线程
*/
private class Worker implements Runnable {
@Override
public void run() {
while (!isShutdown && !Thread.currentThread().isInterrupted()) {
try {
Runnable task = taskQueue.poll(500, TimeUnit.MILLISECONDS);
if (task != null) {
task.run();
completedTasks.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
System.err.println("Task execution error: " + e.getMessage());
}
}
}
}
public void shutdown() {
isShutdown = true;
for (Thread worker : workerThreads) {
worker.interrupt();
}
}
}
1.3 测试代码
java
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
// 测试基础线程池
System.out.println("=== 测试基础线程池 ===");
testBasicThreadPool();
// 测试增强版线程池
System.out.println("\n=== 测试增强版线程池 ===");
testEnhancedThreadPool();
}
private static void testBasicThreadPool() throws InterruptedException {
MyThreadPool pool = new MyThreadPool(4);
// 提交50个任务
for (int i = 0; i < 50; i++) {
final int taskId = i;
pool.submit(() -> {
System.out.println(Thread.currentThread().getName() +
" executing task " + taskId);
try {
Thread.sleep(100); // 模拟任务执行
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
Thread.sleep(2000);
pool.shutdown();
}
private static void testEnhancedThreadPool() {
EnhancedThreadPool pool = new EnhancedThreadPool(
2, // 核心线程数
5, // 队列容量
EnhancedThreadPool.RejectPolicy.CALLER_RUNS, // 拒绝策略
null // 使用默认线程工厂
);
// 提交任务,超过队列容量时会触发拒绝策略
for (int i = 0; i < 10; i++) {
final int taskId = i;
pool.execute(() -> {
System.out.println(Thread.currentThread().getName() +
" executing task " + taskId);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Completed tasks: " + pool.getCompletedTaskCount());
System.out.println("Remaining queue size: " + pool.getQueueSize());
pool.shutdown();
}
}
二、定时器详解
2.1 Timer 基础使用
java
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
/**
* Timer 定时器使用示例
*/
public class TimerExample {
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer("MyTimer", true); // 设置为守护线程
// 一次性延迟任务
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("一次性任务执行于: " + new Date());
}
}, 1000);
// 固定延迟的重复任务
timer.schedule(new TimerTask() {
private int count = 0;
@Override
public void run() {
System.out.println("重复任务执行 #" + (++count) + " 于: " + new Date());
if (count >= 5) {
this.cancel(); // 取消任务
System.out.println("任务已取消");
}
}
}, 2000, 1000); // 2秒后开始,每隔1秒执行
// 固定速率的重复任务
timer.scheduleAtFixedRate(new TimerTask() {
private int count = 0;
@Override
public void run() {
System.out.println("固定速率任务 #" + (++count) + " 于: " + new Date());
try {
Thread.sleep(500); // 模拟任务执行时间
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}, 3000, 1000);
Thread.sleep(10000);
timer.cancel(); // 取消定时器
System.out.println("Timer cancelled");
}
}
2.2 ScheduledExecutorService 使用
java
import java.util.Date;
import java.util.concurrent.*;
/**
* ScheduledExecutorService 使用示例
*/
public class ScheduledExecutorExample {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
System.out.println("开始时间: " + new Date());
// 1. 一次性延迟任务
ScheduledFuture<?> future = scheduler.schedule(() -> {
System.out.println("一次性延迟任务执行于: " + new Date());
return "任务完成";
}, 2, TimeUnit.SECONDS);
// 获取任务结果
try {
String result = (String) future.get();
System.out.println("任务结果: " + result);
} catch (ExecutionException e) {
e.printStackTrace();
}
// 2. 固定速率执行(不考虑任务执行时间)
ScheduledFuture<?> fixedRateFuture = scheduler.scheduleAtFixedRate(() -> {
System.out.println("固定速率任务执行于: " + new Date());
try {
Thread.sleep(800); // 任务执行时间
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, 1, 2, TimeUnit.SECONDS);
// 3. 固定延迟执行(考虑任务执行时间)
ScheduledFuture<?> fixedDelayFuture = scheduler.scheduleWithFixedDelay(() -> {
System.out.println("固定延迟任务执行于: " + new Date());
try {
Thread.sleep(800); // 任务执行时间
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, 1, 2, TimeUnit.SECONDS);
// 10秒后取消任务
scheduler.schedule(() -> {
fixedRateFuture.cancel(false);
fixedDelayFuture.cancel(false);
System.out.println("周期性任务已取消");
}, 10, TimeUnit.SECONDS);
Thread.sleep(15000);
scheduler.shutdown();
// 等待所有任务完成
try {
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
} catch (InterruptedException e) {
scheduler.shutdownNow();
}
System.out.println("调度器已关闭");
}
}
2.3 Timer vs ScheduledExecutorService 对比
java
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Timer 和 ScheduledExecutorService 对比
*/
public class TimerVsScheduledExecutor {
/**
* Timer 的问题:单线程,一个任务异常会影响其他任务
*/
public static void testTimerIssue() {
Timer timer = new Timer();
// 第一个任务:正常任务
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("正常任务执行: " + System.currentTimeMillis());
}
}, 1000, 1000);
// 第二个任务:会抛出异常的任务
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("异常任务开始: " + System.currentTimeMillis());
throw new RuntimeException("任务执行异常");
}
}, 3000);
// 第三个任务:在异常任务之后
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("后续任务执行: " + System.currentTimeMillis());
}
}, 5000);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
}
/**
* ScheduledExecutorService 的优势:异常不会影响其他任务
*/
public static void testScheduledExecutorRobustness() {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
// 第一个任务:正常任务
scheduler.scheduleAtFixedRate(() -> {
System.out.println("正常任务执行: " + System.currentTimeMillis());
}, 1, 1, TimeUnit.SECONDS);
// 第二个任务:会抛出异常的任务
scheduler.schedule(() -> {
System.out.println("异常任务开始: " + System.currentTimeMillis());
throw new RuntimeException("任务执行异常");
}, 3, TimeUnit.SECONDS);
// 第三个任务:在异常任务之后
scheduler.schedule(() -> {
System.out.println("后续任务执行: " + System.currentTimeMillis());
}, 5, TimeUnit.SECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
scheduler.shutdown();
}
public static void main(String[] args) {
System.out.println("=== Timer 单线程问题演示 ===");
testTimerIssue();
System.out.println("\n=== ScheduledExecutorService 健壮性演示 ===");
testScheduledExecutorRobustness();
}
}
三、自定义定时器实现
3.1 定时任务类
java
/**
* 定时任务类
*/
public class MyTimerTask implements Comparable<MyTimerTask> {
private final long executeTime; // 执行时间戳
private final Runnable task; // 要执行的任务
private final long period; // 执行周期(0表示一次性任务)
public MyTimerTask(long delay, Runnable task) {
this(delay, task, 0);
}
public MyTimerTask(long delay, Runnable task, long period) {
this.executeTime = System.currentTimeMillis() + delay;
this.task = task;
this.period = period;
}
@Override
public int compareTo(MyTimerTask other) {
return Long.compare(this.executeTime, other.executeTime);
}
public void run() {
if (task != null) {
task.run();
}
}
public long getExecuteTime() {
return executeTime;
}
public long getPeriod() {
return period;
}
public boolean isPeriodic() {
return period > 0;
}
/**
* 计算下一次执行时间(用于周期性任务)
*/
public MyTimerTask nextScheduledTask() {
if (!isPeriodic()) {
return null;
}
return new MyTimerTask(period, task, period);
}
}
3.2 自定义定时器实现
java
import java.util.PriorityQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 自定义定时器实现
*/
public class MyTimer {
private final PriorityQueue<MyTimerTask> taskQueue;
private final ReentrantLock lock;
private final Condition taskAvailable;
private final Thread schedulerThread;
private volatile boolean shutdown;
public MyTimer() {
this(false);
}
public MyTimer(boolean isDaemon) {
this.taskQueue = new PriorityQueue<>();
this.lock = new ReentrantLock();
this.taskAvailable = lock.newCondition();
this.shutdown = false;
this.schedulerThread = new Thread(this::schedulerLoop, "MyTimer-Scheduler");
this.schedulerThread.setDaemon(isDaemon);
this.schedulerThread.start();
}
/**
* 调度一次性任务
*/
public void schedule(Runnable task, long delay) {
schedule(task, delay, 0);
}
/**
* 调度周期性任务
*/
public void schedule(Runnable task, long delay, long period) {
if (shutdown) {
throw new IllegalStateException("Timer is shutdown");
}
if (delay < 0 || period < 0) {
throw new IllegalArgumentException("Delay and period must be non-negative");
}
MyTimerTask timerTask = new MyTimerTask(delay, task, period);
lock.lock();
try {
taskQueue.offer(timerTask);
taskAvailable.signal(); // 唤醒调度线程
} finally {
lock.unlock();
}
}
/**
* 调度器主循环
*/
private void schedulerLoop() {
while (!shutdown) {
lock.lock();
try {
// 等待队列不为空
while (taskQueue.isEmpty() && !shutdown) {
taskAvailable.await();
}
if (shutdown) {
break;
}
MyTimerTask task = taskQueue.peek();
long currentTime = System.currentTimeMillis();
long waitTime = task.getExecuteTime() - currentTime;
if (waitTime <= 0) {
// 执行时间已到
task = taskQueue.poll();
executeTask(task);
// 如果是周期性任务,重新调度
if (task.isPeriodic()) {
MyTimerTask nextTask = task.nextScheduledTask();
if (nextTask != null) {
taskQueue.offer(nextTask);
}
}
} else {
// 等待直到下一个任务执行时间或新任务到达
taskAvailable.awaitNanos(waitTime * 1_000_000);
}
} catch (InterruptedException e) {
// 响应中断,检查关闭状态
if (shutdown) {
break;
}
} finally {
lock.unlock();
}
}
// 清理剩余任务
cleanup();
}
/**
* 执行任务(在单独的线程中执行,避免阻塞调度线程)
*/
private void executeTask(MyTimerTask task) {
if (task != null) {
// 使用新线程执行任务,避免阻塞调度线程
new Thread(() -> {
try {
task.run();
} catch (Exception e) {
System.err.println("Task execution failed: " + e.getMessage());
e.printStackTrace();
}
}, "MyTimer-TaskExecutor").start();
}
}
/**
* 清理剩余任务
*/
private void cleanup() {
lock.lock();
try {
taskQueue.clear();
} finally {
lock.unlock();
}
}
/**
* 关闭定时器
*/
public void shutdown() {
shutdown = true;
schedulerThread.interrupt();
try {
schedulerThread.join(5000); // 等待5秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* 立即关闭定时器
*/
public void shutdownNow() {
shutdown();
}
/**
* 获取待执行任务数量
*/
public int getPendingTaskCount() {
lock.lock();
try {
return taskQueue.size();
} finally {
lock.unlock();
}
}
}
3.3 自定义定时器测试
java
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 自定义定时器测试
*/
public class MyTimerTest {
public static void main(String[] args) throws InterruptedException {
System.out.println("=== 自定义定时器测试 ===");
MyTimer timer = new MyTimer(true); // 使用守护线程
AtomicInteger counter = new AtomicInteger(0);
// 一次性任务
timer.schedule(() -> {
System.out.println("一次性任务执行于: " + new Date());
}, 2000);
// 固定延迟的周期性任务
timer.schedule(() -> {
int count = counter.incrementAndGet();
System.out.println("周期性任务执行 #" + count + " 于: " + new Date());
if (count >= 5) {
System.out.println("达到执行次数,准备关闭定时器");
timer.shutdown();
}
}, 1000, 1000);
// 监控任务队列
Thread monitorThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("待执行任务数: " + timer.getPendingTaskCount());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
monitorThread.setDaemon(true);
monitorThread.start();
// 等待定时器执行完成
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!timer.getPendingTaskCount() == 0) {
timer.shutdown();
}
System.out.println("测试完成");
}
}
四、性能对比测试
java
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 性能对比测试
*/
public class PerformanceComparison {
private static final int TASK_COUNT = 1000;
private static final int THREAD_COUNT = 4;
public static void main(String[] args) throws InterruptedException {
System.out.println("=== 定时器性能对比测试 ===");
// 测试 Timer
long timerTime = testTimer();
System.out.println("Timer 执行时间: " + timerTime + "ms");
// 测试 ScheduledExecutorService
long schedulerTime = testScheduledExecutor();
System.out.println("ScheduledExecutorService 执行时间: " + schedulerTime + "ms");
// 测试自定义定时器
long myTimerTime = testMyTimer();
System.out.println("MyTimer 执行时间: " + myTimerTime + "ms");
}
private static long testTimer() throws InterruptedException {
Timer timer = new Timer();
CountDownLatch latch = new CountDownLatch(TASK_COUNT);
AtomicInteger completed = new AtomicInteger(0);
long startTime = System.currentTimeMillis();
for (int i = 0; i < TASK_COUNT; i++) {
timer.schedule(new TimerTask() {
@Override
public void run() {
completed.incrementAndGet();
latch.countDown();
}
}, 10); // 10ms后执行
}
latch.await();
long endTime = System.currentTimeMillis();
timer.cancel();
return endTime - startTime;
}
private static long testScheduledExecutor() throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(THREAD_COUNT);
CountDownLatch latch = new CountDownLatch(TASK_COUNT);
AtomicInteger completed = new AtomicInteger(0);
long startTime = System.currentTimeMillis();
for (int i = 0; i < TASK_COUNT; i++) {
scheduler.schedule(() -> {
completed.incrementAndGet();
latch.countDown();
}, 10, TimeUnit.MILLISECONDS);
}
latch.await();
long endTime = System.currentTimeMillis();
scheduler.shutdown();
return endTime - startTime;
}
private static long testMyTimer() throws InterruptedException {
MyTimer timer = new MyTimer();
CountDownLatch latch = new CountDownLatch(TASK_COUNT);
AtomicInteger completed = new AtomicInteger(0);
long startTime = System.currentTimeMillis();
for (int i = 0; i < TASK_COUNT; i++) {
timer.schedule(() -> {
completed.incrementAndGet();
latch.countDown();
}, 10);
}
latch.await();
long endTime = System.currentTimeMillis();
timer.shutdown();
return endTime - startTime;
}
}
总结
核心要点回顾:
-
线程池设计要点:
- 任务队列管理
- 工作线程生命周期管理
- 拒绝策略处理
- 优雅关闭机制
-
定时器实现关键:
- 优先级队列管理定时任务
- 精确的时间等待机制
- 周期性任务重新调度
- 异常处理与容错
-
性能优化建议:
- 使用合适的队列容量
- 合理设置线程数量
- 避免在定时任务中执行耗时操作
- 使用守护线程避免资源泄漏
-
生产环境建议:
- 优先使用
ScheduledExecutorService - 避免使用单线程的
Timer - 合理处理任务异常
- 实现完善的监控和关闭机制
- 优先使用
通过深入理解这些核心概念和实现原理,你能够更好地选择合适的并发工具,并能够根据具体业务需求进行定制化开发。