执行程序线程池问题:执行程序服务没有关闭 [英] issue with executor thread pool : executer service not getting shutdown

查看:223
本文介绍了执行程序线程池问题:执行程序服务没有关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的java程序中,我使用cocurrnent执行线程,使用下面的代码

In my java program I am using cocurrnent execution of threads by using code below

ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
    Thread t1 = new AMDataSend(Q_AM_TO_ID, DATA, MAILER_ID, AM_BATCH_ID, FILE_NAME);
    System.out.println(" thread : " + i);
    executor.execute(t1);
}
executor.shutdown();
System.out.println("pre !executor.isTerminated() : "+(!executor.isTerminated()));
while (!executor.isTerminated()) {

    System.out.println("!executor.isTerminated() : "+(!executor.isTerminated()));
    boolean awaitTermination = executor.awaitTermination(1000, TimeUnit.MILLISECONDS);
    if(awaitTermination){
        break;
    }else{
        System.out.println("not terminated");
    }
}
System.out.println("Finished all threads");





但执行者没有得到关闭而while循环充当无限。我怎样才能解决这个问题?



but the executor not get shutdown and while loop act as infinite. How can I solve this problem?

推荐答案

您好,



检查您的AMDataSend类。可能它正在等待某事或内部有无限循环。您可以按如下方式修改终止检查循环以优先终止工作线程。

Hello,

Check your AMDataSend class. Probably it's waiting for something or has an infinite loop inside. You can modify your termination check loop as follows to forecefully terminate the worker threads.
int cntr = 0;

executor.shutdown(); // Disable new tasks from being submitted
while (!executor.isTerminated() || cntr < 3) {
    boolean awaitTermination = executor.awaitTermination(1000, TimeUnit.MILLISECONDS);
    if (awaitTermination) {
        // All worker threads have completed there unit of work.
        break;
    }
    cntr++;
}
// Check if there are still some lingering threads 
try {
    if (!executor.isTerminated()) {
        executor.shutdownNow(); // Force shutdown
        executor.awaitTermination(1000, TimeUnit.MILLISECONDS); // Wait a while for tasks to respond to being cancelled
    }
}
catch (Exception ex) {
    System.out.println(ex.getMessage());
}



问候,


Regards,


这篇关于执行程序线程池问题:执行程序服务没有关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆