# 48. 线程池任务类型优化分析

# 标准答案

✅ 不同任务类型的线程池优化策略:

  1. CPU密集型任务

    • 线程数 = CPU核心数 + 1
    • 使用固定大小线程池
    • 避免线程切换开销
    • 选择较小的队列容量
  2. I/O密集型任务

    • 线程数 = CPU核心数 * (1 + I/O耗时/CPU耗时)
    • 使用可缓存线程池
    • 允许更多的并发线程
    • 采用SynchronousQueue
  3. 混合型任务

    • 根据I/O比例调整线程数
    • 使用不同的线程池分离任务
    • 实现动态线程数调整
    • 监控任务执行情况

# 答案解析

# 1️⃣ CPU密集型优化

public class CpuIntensivePool {
    private final ThreadPoolExecutor executor;
    
    public CpuIntensivePool() {
        int coreCount = Runtime.getRuntime().availableProcessors();
        executor = new ThreadPoolExecutor(
            coreCount + 1,  // 核心线程数
            coreCount + 1,  // 最大线程数
            60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
        
        // 预热核心线程
        executor.prestartAllCoreThreads();
    }
    
    public <T> Future<T> submit(Callable<T> task) {
        return executor.submit(() -> {
            // 设置线程优先级
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
            return task.call();
        });
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 2️⃣ I/O密集型优化

public class IoIntensivePool {
    private final ThreadPoolExecutor executor;
    
    public IoIntensivePool(double ioRatio) {
        int coreCount = Runtime.getRuntime().availableProcessors();
        int threadCount = (int)(coreCount * (1 + ioRatio));
        
        executor = new ThreadPoolExecutor(
            threadCount,
            threadCount * 2,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<>(),
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    // I/O线程使用较低优先级
                    t.setPriority(Thread.NORM_PRIORITY - 1);
                    return t;
                }
            }
        );
    }
    
    public void executeIoTask(Runnable task) {
        executor.execute(() -> {
            try {
                task.run();
            } catch (Exception e) {
                // 处理I/O异常
                handleIoException(e);
            }
        });
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# 常见误区

  • 误区1:线程数越多性能越好
  • 误区2:忽视任务类型特征

# 典型场景与解决方案

# ✅ 混合任务处理

public class HybridTaskExecutor {
    private final ThreadPoolExecutor cpuPool;
    private final ThreadPoolExecutor ioPool;
    
    public HybridTaskExecutor() {
        int coreCount = Runtime.getRuntime().availableProcessors();
        
        // CPU密集型线程池
        cpuPool = new ThreadPoolExecutor(
            coreCount + 1,
            coreCount + 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1000)
        );
        
        // I/O密集型线程池
        ioPool = new ThreadPoolExecutor(
            coreCount * 2,
            coreCount * 4,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<>()
        );
    }
    
    public void executeTask(Task task) {
        switch (task.getType()) {
            case CPU_INTENSIVE:
                cpuPool.execute(task);
                break;
            case IO_INTENSIVE:
                ioPool.execute(task);
                break;
            default:
                throw new IllegalArgumentException("Unknown task type");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

# 企业实战经验

# Situation(业务背景)

系统同时处理计算任务和文件处理任务,性能表现不佳。

# Task(核心任务)

优化不同类型任务的线程池配置。

# Action(解决方案)

  1. 分离不同类型任务
  2. 针对性优化配置
  3. 实现任务分类
  4. 监控性能指标

# Result(结果)

  • CPU利用率提升40%
  • I/O处理能力提升200%
  • 系统响应更稳定

# 深入追问

🔹 如何识别任务类型?

  • 分析执行时间分布
  • 监控资源使用情况
  • 评估I/O等待比例

🔹 如何处理任务类型动态变化?

  • 实现自适应调整
  • 监控任务特征
  • 动态切换线程池

# 相关面试题

  1. 如何确定最优线程数?
  2. 不同等待策略的选择?
  3. 如何处理任务优先级?