如何在Java中杀死Java .lang. thread ?
当前回答
请参阅Sun的这篇文章,了解他们为什么弃用thread .stop()。它将详细说明为什么这是一个糟糕的方法,以及应该做些什么来安全地停止线程。
他们推荐的方法是使用一个共享变量作为标志,要求后台线程停止。这个变量可以由请求线程终止的另一个对象设置。
其他回答
请参阅Sun的这篇文章,了解他们为什么弃用thread .stop()。它将详细说明为什么这是一个糟糕的方法,以及应该做些什么来安全地停止线程。
他们推荐的方法是使用一个共享变量作为标志,要求后台线程停止。这个变量可以由请求线程终止的另一个对象设置。
在Java中,线程不会被杀死,但是线程的停止是通过协作的方式完成的。线程被要求终止,然后线程可以优雅地关闭。
通常使用一个易失性布尔字段,线程定期检查,并在设置为相应值时终止。
我不会使用布尔值来检查线程是否应该终止。如果你使用volatile作为字段修饰符,这将可靠地工作,但如果你的代码变得更复杂,而不是在while循环中使用其他阻塞方法,它可能会发生,你的代码根本不会终止,或者至少需要更长的时间。
某些块库方法支持中断。
每个线程已经有一个布尔标志中断状态,你应该利用它。它可以这样实现:
public void run() {
try {
while (!interrupted()) {
// ...
}
} catch (InterruptedException consumed)
/* Allow thread to exit */
}
}
public void cancel() { interrupt(); }
源代码改编自Java并发实践。因为cancel()方法是公共的,你可以让另一个线程按你的意愿调用这个方法。
一般来说你不会…
你可以使用Thread.interrupt() (javadoc link)命令它中断正在做的事情。
在javadoc中有一个很好的解释(java technote链接)
通常不杀死、停止或中断线程(或检查它是否被中断()),而是让它自然终止。
这很简单。你可以在run()方法中使用任何循环和(volatile)布尔变量来控制线程的活动。您还可以从活动线程返回到主线程以停止它。
这样你就优雅地杀死了一个线程:)。
没有办法优雅地终止线程。
您可以尝试中断线程,一个常用的策略是使用毒丸来通知线程停止自己
public class CancelSupport {
public static class CommandExecutor implements Runnable {
private BlockingQueue<String> queue;
public static final String POISON_PILL = “stopnow”;
public CommandExecutor(BlockingQueue<String> queue) {
this.queue=queue;
}
@Override
public void run() {
boolean stop=false;
while(!stop) {
try {
String command=queue.take();
if(POISON_PILL.equals(command)) {
stop=true;
} else {
// do command
System.out.println(command);
}
} catch (InterruptedException e) {
stop=true;
}
}
System.out.println(“Stopping execution”);
}
}
}
BlockingQueue<String> queue=new LinkedBlockingQueue<String>();
Thread t=new Thread(new CommandExecutor(queue));
queue.put(“hello”);
queue.put(“world”);
t.start();
Thread.sleep(1000);
queue.put(“stopnow”);
http://anandsekar.github.io/cancel-support-for-threads/