java 线程回收_Java线程池任务执行完毕后回收线程

当Java线程池中的任务执行完毕后,线程并未自动回收可能导致JVM OOM问题。解决方法包括:1) 设置`allowCoreThreadTimeOut(true)`并在创建线程池后立即设置,确保`keepAliveTime`大于0;2) 在所有任务执行完毕后调用`shutdown()`方法回收空闲线程,此时`keepAliveTime`参数失效。
摘要由CSDN通过智能技术生成

线程池中的所有任务执行完毕后,线程并没有停止,导致JVM出现OOM问题。后来查找了下面链接的资料,解决问题。

问题及现象:

public static void main(String[] args) {

BlockingQueue queue = new LinkedBlockingQueue();

ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 10, TimeUnit.SECONDS, queue);

for (int i = 0; i < 20; i++) {

executor.execute(new Runnable() {

@Override

public void run() {

try {

System.out.println(this.hashCode() / 1000);

for (int j = 0; j < 10; j++) {

System.out.println(this.hashCode() + ":" + j);

Thread.sleep(this.hashCode() % 2);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(String.format("thread %d finished", this.hashCode()));

}

});

}

}

74e4f16c869a

image.png

任务已经执行完毕了,但是线程池中的线程并没有被回收,程序任然处于运行状态。但是在ThreadPoolExecutor的参数里面设置了超时时间的,好像没起作用,原因如下:

工作线程回收需要满足三个条件:

参数allowCoreThreadTimeOut为true

该线程在keepAliveTime时间内获取不到任务,即空闲这么长时间

当前线程池大小 > 核心线程池大小corePoolSize。

解决一:allowCoreThreadTimeOut设置为true

public static void method1() {

BlockingQueue queue = new LinkedBlockingQueue();

ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 1, TimeUnit.SECONDS, queue);

executor.allowCoreThreadTimeOut(true);

for ( int i = 0; i < 20; i++) {

executor.execute( new Runnable() {

public void run() {

try {

System. out.println( this.hashCode()/1000);

for ( int j = 0; j < 10; j++) {

System. out.println( this.hashCode() + ":" + j);

Thread. sleep(this.hashCode()%2);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

System. out.println(String. format("thread %d finished", this.hashCode()));

}

});

}

}

需要注意的是,allowCoreThreadTimeOut 的设置需要在任务执行之前,一般在new一个线程池后设置;在allowCoreThreadTimeOut设置为true时,ThreadPoolExecutor的keepAliveTime参数必须大于0。

解决二:调用shutdown方法

public static void method1() {

BlockingQueue queue = new LinkedBlockingQueue();

ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 1, TimeUnit.SECONDS, queue);

for ( int i = 0; i < 20; i++) {

executor.execute( new Runnable() {

public void run() {

try {

System. out.println( this.hashCode()/1000);

for ( int j = 0; j < 10; j++) {

System. out.println( this.hashCode() + ":" + j);

Thread. sleep(this.hashCode()%2);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

System. out.println(String. format("thread %d finished", this.hashCode()));

}

});

}

executor.shutdown();

}

在任务执行完后,调用shutdown方法,将线程池中的空闲线程回收。该方法会使得keepAliveTime参数失效。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值