如何在 Executor Service 中停止长时间执行任务(例如无限循环)的执行 [英] How to Stop long duration execution task ( e.g. Infinite Loop) execution inside a Executor Service

查看:119
本文介绍了如何在 Executor Service 中停止长时间执行任务(例如无限循环)的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个示例程序.如果我取消注释 Thread.sleep 它工作正常.但是可能有一些需要,我们不确定写在 Call 方法里面的代码需要多少时间,可以是无限的时间.或者,可能是一个糟糕的程序,其中 Call 方法中的数据库连接逻辑需要更多时间,我们需要杀死.

Below is a sample program. If i uncomment the Thread.sleep it works fine. But there may be some need, where we are not sure how much time the code written inside Call method takes, can be a infinite time. Or, can be a bad program where the DB connection logic inside Call method takes more time and we need to kill.

如果我评论 thread.sleep 以及如何在不编写 Thread.interrupted 条件的情况下杀死和停止它,你能告诉我为什么下面的代码不起作用.(假设我没有权限在 Call 方法中写入任何逻辑)

Could you please tell, why the below code does not work if i comment the thread.sleep and how to kill and stop that without writing Thread.interrupted condition. (Assume i do not have permission write any logic inside the Call method)

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class stopThreadTest {

    public static void main(String[] args) {

        java.util.concurrent.ExecutorService executor = null;
        Future a1 = null;

        try {
            executor = java.util.concurrent.Executors.newFixedThreadPool(4);
            a1 = executor.submit(new java.util.concurrent.Callable() {
                public String call() throws Exception {
                    int i = 0;
                    while (true) {
                        //Thread.sleep(100);
                        // System.out.println("hello");
                        if (i > 10)
                            break;
                    }
                    return null;
                }
            });

            // Wait until all threads are finish
            /*
             * while (!executor.isTerminated()) { }
             */
            System.out.println("Calling PartialOrFullSuccessCheck");

            try {
                boolean isThreadError = (a1 != null) ? ((a1.get(2,
                        TimeUnit.SECONDS) == null) ? false : true) : false;

            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);

                System.out.println("encountered problem while doing some work");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

                // interrupts the worker thread if necessary
                System.out
                        .println("Cancelled" + a1.isDone() + a1.isCancelled());
                a1.cancel(true);
            }

        } finally {
            System.out.println("ShutDown Executor");
            executor.shutdown();
        }
    }
}

推荐答案

没有线程的合作,没有安全的方法来停止线程.线程允许其他线程通过被中断、定期检查某些共享变量的值或两者来停止它们.除此之外,唯一安全的做法是关闭 JVM(整个过程).这篇文章很详细:

There is no safe way to stop a thread without its cooperation. Threads allow other threads to stop them by being interrupted, by periodically checking the value of some shared variable or both. Other than that, the only safe thing to do is shut down the JVM (the whole process). This post is quite detailed:

如何在 Java 中杀死线程?

这篇关于如何在 Executor Service 中停止长时间执行任务(例如无限循环)的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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