JVM中的线程池是如何工作的?如何配置和优化线程池?
困难JVM线程池
💬0
🔥0
👍0
详细说明JVM中线程池的工作原理,包括线程池参数、工作流程、配置策略等核心内容
参考答案
线程池是JVM中管理线程的重要机制,通过复用线程减少创建和销毁的开销:
- 线程池基本概念
核心组件
- 核心线程数(corePoolSize):常驻线程数量
- 最大线程数(maximumPoolSize):最大线程数量
- 工作队列(workQueue):存储等待执行的任务
- 线程工厂(threadFactory):创建新线程
- 拒绝策略(rejectedExecutionHandler):处理无法执行的任务
工作流程
-
提交任务到线程池
-
如果核心线程数未满,创建新线程执行任务
-
如果核心线程数已满,将任务放入工作队列
-
如果工作队列已满,创建新线程执行任务
-
如果达到最大线程数,执行拒绝策略
-
常用线程池类型
FixedThreadPool
public class FixedThreadPoolExample {
public void useFixedThreadPool() {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " executed by " +
Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
CachedThreadPool
public class CachedThreadPoolExample {
public void useCachedThreadPool() {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " executed by " +
Thread.currentThread().getName());
});
}
executor.shutdown();
// 设置垃圾回收器参数
System.setProperty("java.vm.name", "Dalvik");
// 监控内存使用
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
Log.d("JVM", "Max Memory: " + maxMemory / 1024 / 1024 + "MB");
Log.d("JVM", "Total Memory: " + totalMemory / 1024 / 1024 + "MB");
Log.d("JVM", "Free Memory: " + freeMemory / 1024 / 1024 + "MB");
// 手动触发垃圾回收(仅用于测试)
if (freeMemory < maxMemory * 0.1) { // 可用内存少于10%
System.gc();
Log.d("JVM", "Manual GC triggered");
}
}
// 内存泄漏检测
private void detectMemoryLeak() {
// 使用WeakReference避免内存泄漏
WeakReference<Context> contextRef = new WeakReference<>(getApplicationContext());
// 检查引用是否被回收
if (contextRef.get() == null) {
Log.d("JVM", "Context has been garbage collected");
}
}
GC monitor
public class GCMonitor {
private static final String TAG = "GCMonitor";
private long lastGCTime = 0;
private int gcCount = 0;
public void onGarbageCollection() {
long currentTime = System.currentTimeMillis();
long interval = currentTime - lastGCTime;
gcCount++;
Log.d(TAG, "GC #" + gcCount + " occurred after " + interval + "ms");
lastGCTime = currentTime;
// 分析GC频率
if (interval < 1000) { // 1秒内发生GC
Log.w(TAG, "High GC frequency detected - possible memory pressure");
}
}
}
评论区 (0)
暂无评论,来发表第一条评论吧!