java - 如何停止执行器服务内的长时间执行任务(例如无限循环)执行

标签 java multithreading

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

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

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(整个进程)。这篇文章非常详细:

How do you kill a thread in Java?

关于java - 如何停止执行器服务内的长时间执行任务(例如无限循环)执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10853305/

相关文章:

java - 需要为每个 webservcie 调用创建 javax.ws.rs.client.Client

java - java中的并行流

java - 作为 Spring Boot 应用程序运行无法正常运行,而作为 Java 应用程序运行则无法正常运行

java - Java 中连接字符串会生成 Between-in null

java - 改造 2 : @Query "encoded=false" don't work

c - pthread_mutex_lock() 上的段错误

c - 在C中使用Windows API进行多线程

java - 如何确定HashMap中方法的最坏情况复杂度?

multithreading - 有没有办法让两次读取原子化?

.net - Console.In.ReadLine(重定向的StdIn)卡住所有其他线程