如何在Java中杀死Java .lang. thread ?
当前回答
在Java中,线程不会被杀死,但是线程的停止是通过协作的方式完成的。线程被要求终止,然后线程可以优雅地关闭。
通常使用一个易失性布尔字段,线程定期检查,并在设置为相应值时终止。
我不会使用布尔值来检查线程是否应该终止。如果你使用volatile作为字段修饰符,这将可靠地工作,但如果你的代码变得更复杂,而不是在while循环中使用其他阻塞方法,它可能会发生,你的代码根本不会终止,或者至少需要更长的时间。
某些块库方法支持中断。
每个线程已经有一个布尔标志中断状态,你应该利用它。它可以这样实现:
public void run() {
try {
while (!interrupted()) {
// ...
}
} catch (InterruptedException consumed)
/* Allow thread to exit */
}
}
public void cancel() { interrupt(); }
源代码改编自Java并发实践。因为cancel()方法是公共的,你可以让另一个线程按你的意愿调用这个方法。
其他回答
There is of course the case where you are running some kind of not-completely-trusted code. (I personally have this by allowing uploaded scripts to execute in my Java environment. Yes, there are security alarm bell ringing everywhere, but it's part of the application.) In this unfortunate instance you first of all are merely being hopeful by asking script writers to respect some kind of boolean run/don't-run signal. Your only decent fail safe is to call the stop method on the thread if, say, it runs longer than some timeout.
但是,这只是“体面的”,而不是绝对的,因为代码可以捕获ThreadDeath错误(或您显式抛出的任何异常),而不是像一个绅士线程应该做的那样重新抛出它。所以,AFAIA的底线是没有绝对的故障保险。
没有办法优雅地终止线程。
您可以尝试中断线程,一个常用的策略是使用毒丸来通知线程停止自己
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/
我没有得到中断工作在Android,所以我用这个方法,工作完美:
boolean shouldCheckUpdates = true;
private void startupCheckForUpdatesEveryFewSeconds() {
Thread t = new Thread(new CheckUpdates());
t.start();
}
private class CheckUpdates implements Runnable{
public void run() {
while (shouldCheckUpdates){
//Thread sleep 3 seconds
System.out.println("Do your thing here");
}
}
}
public void stop(){
shouldCheckUpdates = false;
}
请参阅Sun的这篇文章,了解他们为什么弃用thread .stop()。它将详细说明为什么这是一个糟糕的方法,以及应该做些什么来安全地停止线程。
他们推荐的方法是使用一个共享变量作为标志,要求后台线程停止。这个变量可以由请求线程终止的另一个对象设置。
一种方法是设置一个类变量并将其用作哨兵。
Class Outer {
public static volatile flag = true;
Outer() {
new Test().start();
}
class Test extends Thread {
public void run() {
while (Outer.flag) {
//do stuff here
}
}
}
}
设置一个外部类变量,如上面例子中的flag = true。将其设置为false以“杀死”线程。
推荐文章
- 从枚举中选择一个随机值?
- 如何从URL获取参数与JSP
- 如何在Eclipse中生成Javadoc注释?
- 找到java类从哪里加载
- 从集合中随机选取一个元素
- 为什么x == (x = y)和(x = y) == x不一样?
- 什么Java 8流。收集等价物可在标准Kotlin库?
- 等待未来的名单
- 如何检查JSON键是否存在?
- 为什么MongoDB Java驱动在条件中使用随机数生成器?
- 即使从未抛出异常,使用try-catch块的代价是否昂贵?
- 什么时候我们应该使用观察者和可观察对象?
- Java中的split()方法对点(.)不起作用。
- Eclipse调试器总是阻塞在ThreadPoolExecutor上,没有任何明显的异常,为什么?
- Java生成两个给定值之间的随机数