MST

星途 面试题库

面试题:Java线程池中如何设计简单的告警规则

假设你正在使用Java线程池,当线程池中的活跃线程数达到核心线程数的1.5倍时,你需要触发一个告警。请简述实现该告警规则的大致思路,并给出关键代码片段。
36.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

大致思路

  1. 创建线程池时,记录核心线程数。
  2. 通过ScheduledExecutorService定时检查线程池的活跃线程数。
  3. 将活跃线程数与核心线程数的1.5倍进行比较,如果超过则触发告警。

关键代码片段

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolAlarm {

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5, 10, 10L, TimeUnit.SECONDS,
            new java.util.concurrent.LinkedBlockingQueue<>());

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) {
        startAlarmCheck();

        // 模拟提交任务
        for (int i = 0; i < 10; i++) {
            executor.submit(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
    }

    private static void startAlarmCheck() {
        ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(() -> {
            int activeCount = executor.getActiveCount();
            int corePoolSize = executor.getCorePoolSize();
            if (activeCount > corePoolSize * 1.5) {
                System.out.println("告警:活跃线程数超过核心线程数的1.5倍,当前活跃线程数:" + activeCount);
            }
        }, 0, 1, TimeUnit.SECONDS);
    }
}