我遇到了停止线程的不同建议。我可以知道,这是正确的方法吗?还是视情况而定?
使用线程变量 http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
使用 boolean 标志
private volatile boolean flag;
public void stop() {
flag = false;
}
public void run() {
while (flag) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
将线程变量与中断一起使用
private volatile Thread blinker;
public void stop() {
blinker.interrupt();
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (!thisThread.isInterrupted() && blinker == thisThread) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
最佳答案
这些都不是“正确”的方式,它们都是有效的。您使用哪一种取决于您的情况,哪一种最适合您。
只要您不使用 Thread.stop()
,并且您清理线程打开的所有资源(连接、临时文件等),那么它实际上并没有无论你如何去做。
关于java - 停止线程的各种方法——这是正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4705709/