Debian上Java线程管理的实操指南
一 环境准备与基础
二 线程同步与通信
三 线程池与任务调度
四 监控与调优实践
五 最小可运行示例
import java.util.concurrent.*;
public class ThreadPoolDemo {
public static void main(String[] args) throws InterruptedException {
int cores = Runtime.getRuntime().availableProcessors();
ExecutorService exec = new ThreadPoolExecutor(
cores, cores * 2,
60L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100),
new ThreadFactory() {
private final ThreadFactory df = Executors.defaultThreadFactory();
private int n = 0;
public Thread newThread(Runnable r) {
Thread t = df.newThread(r);
t.setName("worker-" + (++n));
t.setDaemon(false);
return t;
}
},
new ThreadPoolExecutor.CallerRunsPolicy()
);
for (int i = 0; i < 200; i++) {
final int taskId = i;
exec.submit(() -> {
try {
// 模拟业务:I/O 或计算
Thread.sleep(10);
if (taskId % 50 == 0) System.out.println("Processed " + taskId);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
exec.shutdown();
if (!exec.awaitTermination(30, TimeUnit.SECONDS)) {
exec.shutdownNow();
}
}
}