面试题答案
一键面试实现思路
- 自定义一个类实现
RejectedExecutionHandler
接口,该接口只有一个rejectedExecution
方法,当任务被拒绝时会调用此方法。 - 在
rejectedExecution
方法中获取当前时间戳,并将任务信息和时间戳记录到日志文件中。
关键代码示例
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
long timestamp = System.currentTimeMillis();
Date date = new Date(timestamp);
try (PrintWriter out = new PrintWriter(new FileWriter("rejected_tasks.log", true))) {
out.println("Task " + r.toString() + " rejected at " + date);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用时在创建 ThreadPoolExecutor
时传入自定义的拒绝策略:
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(queueCapacity),
new CustomRejectedExecutionHandler()
);