【问题标题】:Java 8: Kill/Stop a thread after certain period of timeJava 8:在一段时间后杀死/停止线程
【发布时间】:2017-10-03 05:36:51
【问题描述】:

我有一个基于 java 8 的项目,它在 url 上执行特定功能。我需要修改下面的代码 sn-p 以便它能够杀死正在运行的线程/进程并在一段时间后运行下一个实例,而不管当前进程状态如何。

我尝试了以下技术来实现线程终止过程:

  • 执行者服务
  • 定时器任务
  • 多线程线程终止

我最近尝试的代码 sn-p 链接如下。

@SuppressWarnings("static-access")
public static void main(String[] args) {
//fetch url from the txt file
    List<String> careerUrls = getCareerUrls();
    int a = 0;
    DBConnection ds = null;
    ds = DBConnection.getInstance();
    try (java.sql.Connection con = ds.getConnection()) {
        //read a single Url
        for (String url : careerUrls) {
            int c = a++;

            ExecutorService executor = Executors.newFixedThreadPool(3);

            Future<?> future = executor.submit(new Runnable() {
                @Override
                // <-- job processing
                public void run() {
                    long end_time = System.currentTimeMillis() + 10000;

                    System.out.println("STARTED PROCESSING URL: " + url);
                    jobareaDeciderSample w = new jobareaDeciderSample();
                    w.mainSample(url, c, con);

                }
            });
            // <-- reject all further submissions
            executor.shutdown();
            try {
                future.get(120, TimeUnit.SECONDS); // <-- wait 2 Minutes to finish
            } catch (InterruptedException e) { // <-- possible error cases
                System.out.println("job was interrupted");
                future.cancel(true);
                Thread.currentThread().interrupt();
                ;
            } catch (ExecutionException e) {
                System.out.println("caught exception: " + e.getCause());
            } catch (TimeoutException e) {
                System.out.println("timeout");
                future.cancel(true);

            }

            // wait all unfinished tasks for 2 sec
            if (!executor.awaitTermination(0, TimeUnit.SECONDS)) {
                // force them to quit by interrupting
                executor.shutdownNow();
            }
        }

    } catch (Exception e) {
        LOGGER.error(e);
    }

}

【问题讨论】:

    标签: java multithreading java-8 threadpool executorservice


    【解决方案1】:

    您的方法是正确的。 在 future 上调用 cancel(true); 是停止此任务的正确方法。

    你还有另一个问题——你不能仅仅停止一个线程。 (你可以,在线程类中使用 stop(),但你不应该这样做)。

    cancel(true); 向线程发送信息,表明它应该被停止。一些 java 类正在响应此信息并抛出中断的异常。但有些没有。你必须修改你的任务代码,检查是否Thread.currentThread().isInterrupted(),如果是,停止执行。

    这是你必须在你的代码中做的事情,你调用它

      jobareaDeciderSample w = new jobareaDeciderSample();
                        w.mainSample(url, c, con);
    

    您应该在一些长时间的旋转代码中执行此操作,如果您说您使用 url 做一些事情,您应该在您的 while 循环中执行此操作,您可以在其中下载网络信息。换句话说,仅当您的代码花费 99% 的时间时才执行此检查。

    你也在打电话

            Thread.currentThread().interrupt();
    

    在你的主线程中,这对你没有任何作用,如果你想退出当前线程,你可以调用 return

    【讨论】:

    • 你应该使用Thread.interrupted() 来测试你自己线程的中断,如果你要对它做出反应。这也将清除状态。 someThreadInstance.isInterrupted() 方法用于监控状态,当你不处理它时(可能你甚至从不同的线程调用它),所以状态不会受到影响。
    猜你喜欢
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多