执行程序线程池问题:执行程序服务没有关闭

问题描述:

在我的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,