[英]Stopping a thread in an executor service
我面临一种情况,需要停止执行Executor服务的线程。
我已经阅读过其他文章中的解决方案,其中指出要使用Future对象并取消任务。
但是我宁愿尝试另一种方法。
请有人让我知道这种方法是否有任何问题。
以下是我的Runnable课。
public class TestRunnable implements Runnable {
Thread t;
@Override
public void run() {
// TODO Auto-generated method stub
setT(Thread.currentThread());
while(true)
{
if(Thread.currentThread().isInterrupted())
{
System.out.println("From Inside thread, Exiting");
System.exit(0);
}
}
}
public void setT(Thread t) {
this.t = t;
}
public Thread getT() {
return t;
}
}
以下是我的主要方法:
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ruunTest {
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
ExecutorService service = Executors.newCachedThreadPool();
TestRunnable test = new TestRunnable();
service.execute(test);
Thread.sleep(1000);
System.out.println("About to Interrupt");
test.getT().interrupt();
}
}
唯一正确的方法是cancel
与您的任务相对应的Future
,并且在您的任务中,您应定期检查线程是否已中断。
像这样:
public class Task implements Callable<Void> {
@Override
public Void call() throws InterruptedException {
while(true) {
// Check regularly in your code if the thread has been
// interrupted and if so throws an exception to stop
// the task immediately
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Thread interrupted");
}
}
}
}
那么您的主要代码将是:
ExecutorService service = Executors.newCachedThreadPool();
// My task
Task task = new Task();
// Submit the task and get the corresponding future
Future<?> future = service.submit(task);
...
// Cancel the task which will interrupt the thread that was executing the
// task if any
future.cancel(true);
主动停止线程不是一个好主意。 您的代码没有停止线程,它实际上阻止了整个JVM表单的进一步发展。 您实际上错过了执行程序服务的全部要点。
执行者的思想是“我”有一个扩展/收缩的线程列表,可以为您完成工作。 “你”只是给我单独的,互斥的工作行动(Runnables或Callables)。 在这里要理解的要点是“您不必担心线程及其生命周期”……您只需创建工作项并将其交给我执行即可。 如果您不想执行工作或不想在中间调用cancel
方法,则不必担心,因为一旦完成,“ I”将完成并清理并为您提供返回值(如果有)。
“我”还将为您管理线程池,但是当工作作业进入更快时,它会使用更多线程来扩展它,并在工作涌入频率较低时通过“关闭空闲线程”将其收缩为更少的线程。
现在告诉我,您要实现的目标是对的。
尝试使用thread.interrupt()
但不建议这样做 。
您可以将Quasar库用于线程,比Java本机线程运行更快,并且更易于使用。 http://www.paralleluniverse.co/quasar/
您可以使用thread.stop
,尽管它会引发threadDeathError,需要处理。
如果使用future.cancel
,它将取消任务,但不会杀死线程,因为线程将返回线程池。 Thread.stop
将杀死线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.