Future.cancel()方法不工作

编程入门 行业动态 更新时间:2024-10-09 14:18:43
本文介绍了Future.cancel()方法不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建一个Callable实例并使用ExecutorService创建一个新线程的代码。我想杀了这个线程在一定的时间后,如果线程没有完成它的执行。在通过jdk文档后,我意识到Future.cancel()方法可以用来停止线程的执行,但是对我来说,它不工作。当然future.get()方法在规定的时间(在我的情况下它的2秒)之后向线程发送中断,甚至线程正在接收这个中断,但是这个中断仅在线程完成其执行时发生完全。但我想在2秒后杀死线程。

The code that I have creates a Callable instance and using ExecutorService a new thread is being created. I want to kill this thread after certain amount of time if the thread is not done with its execution. After going through the jdk documentation I've realized that Future.cancel() method can be used to stop the execution of the thread, but to my dismay its not working. Of course future.get() method is sending an interrupt to the Thread after the stipulated time (in my case its 2 seconds) and even the thread is receiving this interrupt but this interruption is taking place only once the thread is done with its execution completely. But I want to kill the thread after 2 seconds.

任何人都可以帮助我如何实现这一点。

Could anyone help me how to achieve this.

测试类代码:

==================================== public class TestExecService { public static void main(String[] args) { //checkFixedThreadPool(); checkCallablePool(); } private static void checkCallablePool() { PrintCallableTask task1 = new PrintCallableTask("thread1"); ExecutorService threadExecutor = Executors.newFixedThreadPool(1); Future<String> future = threadExecutor.submit(task1); try { System.out.println("Started.."); System.out.println("Return VAL from thread ===>>>>>" + future.get(2, TimeUnit.SECONDS)); System.out.println("Finished!"); } catch (InterruptedException e) { System.out.println("Thread got Interrupted Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>"); //e.printStackTrace(); } catch (ExecutionException e) { System.out.println("Thread got Execution Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>"); } catch (TimeoutException e) { System.out.println("Thread got TimedOut Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>"); future.cancel(true); } threadExecutor.shutdownNow(); } }

可调用类代码:

=================================================================== package com.test; import java.util.concurrent.Callable; public class PrintCallableTask implements Callable<String> { private int sleepTime; private String threadName; public PrintCallableTask(String name) { threadName = name; sleepTime = 100000; } @Override public String call() throws Exception { try { System.out.printf("%s going to sleep for %d milliseconds.\n", threadName, sleepTime); int i = 0; while (i < 100000) { System.out.println(i++); } Thread.sleep(sleepTime); // put thread to sleep System.out.printf("%s is in middle of execution \n", threadName); } catch (InterruptedException exception) { exception.printStackTrace(); } System.out.printf("%s done sleeping\n", threadName); return "success"; } }

推荐答案

您的代码会做到一切正常。唯一的问题是你不在 while 循环中检查 Thread.isInterrupted 。线程得到消息的唯一方法是得到阻塞调用 Thread.sleep ,它会立即引发 InterruptedException 。 如果循环很长,可能需要一些时间。

Your code does everything right. The only problem is that you're not checking Thread.isInterrupted in the while loop. The only way for thread to get the message is to get to the blocking call Thread.sleep which will immediately throw InterruptedException. If loop is lengthy it can take some time. That's exactly why your code is a little bit unresponsive.

检查中断状态,例如每10,000次迭代:

Check for interruption status, say, every 10,000 iterations:

while (i < 100000) { if (i % 10000 == 0 && Thread.currentThread().isInterrupted()) return "fail"; System.out.println(i++); }

InterruptedException 冗长阻塞方法。 Thread.isInterrupted 是其他所有的。

InterruptedException is for lengthy blocking methods. Thread.isInterrupted is for everything else.

更多推荐

Future.cancel()方法不工作

本文发布于:2023-11-25 21:24:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631403.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   工作   Future   cancel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!