[英]How can I safely stop my “class implements Runnable”?
Oracle Java SE Docs建議這樣做:
您可以通過將applet的stop和run方法替換為:來避免使用Thread.stop:
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
有沒有一種方法可以為class blinker implements Runnable
做同樣的事情?
因為您將不得不使用blinker thisClass = this;
或類似的東西, (blinker == thisClass)
總是不等於true嗎?
或者此代碼足以滿足要求:
class blinker implements Runnable {
boolean stop = false;
@override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// code
// ...
if (stop) { Thread.currentThread().interrupt(); }
// ...
}
}
}
您可以這樣做:
class Blinker implements Runnable {
Runnable blinker = this;
public void stop() {
blinker = null;
}
public void run() {
while(blinker == this) {
}
}
}
但這將毫無意義。 我認為您沒有理解文檔試圖解決的問題 ,即不要使用無限循環來使線程保持活動,而要使用Thread#stop()
終止Thread#stop()
。 而是使用條件,然后在要結束使線程保持活動狀態的循環時將其設置為false。
您無需經常檢查Thread#isInterrupted()
即可保持線程存活。
while(!stop) {
}
會做的很好。 您也不應從線程內部中斷線程。 中斷的目的是結束暫停線程的任務。 這些任務包含在try/catch
,捕獲了InterruptedException
。 其他線程通常是負責中斷的線程。
該文檔是指允許線程正常退出。
在第一個示例中, run()
方法是通過無限循環處理的: while(true)
。 停止線程的唯一方法是強制某種停止,例如usong Thread#stop
:
public void run() {
while (true) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
但是不建議使用Thread#stop
。 相反,循環應取決於boolean
,另一個線程(或當前線程)可以將其設置為true
或false
:
private volatile boolean running;
public void stop() {
running = false;
}
public void run() {
while (running) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
而不是使用的running
布爾,他們用blinker == thisThread
,然后改變的值blinker
,當他們想要結束循環:
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.