0
我有一個帶有swing GUI的程序,並且當我的一個JFrame被丟棄時我想中斷一個線程。有沒有快速的方法來做到這一點?這是我第一次使用併發。有沒有辦法將線程的命運與對象綁定?
我有一個帶有swing GUI的程序,並且當我的一個JFrame被丟棄時我想中斷一個線程。有沒有快速的方法來做到這一點?這是我第一次使用併發。有沒有辦法將線程的命運與對象綁定?
是的,你可以做到以下幾點:
創建一個JFrame子類並覆蓋Dispose()方法:
class MyFrame extends JFrame{
private Thread otherThread;
public MyFrame(Thread otherThread){
super("MyFrame");
this.otherThread=otherThread;
}
...
public void dispose(){
otherThread.interrupt();
super.dispose();
}
}
然而,請注意了Thread.interrupt的使用()是不鼓勵的,因爲實際上不可能控制線程在哪個狀態中斷。
因此,最好爲您自己的Thread(或Runnable)子類手動維護一個'中斷'標誌,並讓Thread停止它認爲合適的工作。
例如:
class MyThread extends Thread{
private boolean interrupted=false;
public void interruptMyThread(){
interrupted=true;
}
public void run(){
while(true){
// ... some work the thread does
// ... a point in the thread where it's safe
// to stop...
if(interrupted){
break;
}
}
}
}
然後,代替具有在MyFrame一個Thread引用,使用一個參考MyThread的,而不是調用otherThread.interrupt()
,呼叫otherThread.interruptMyThread()
。
所以,最終MyFrame類看起來是這樣的:
class MyFrame extends JFrame{
private MyThread otherThread;
public MyFrame(MyThread otherThread){
super("MyFrame");
this.otherThread=otherThread;
}
...
public void dispose(){
otherThread.interruptMyThread();
super.dispose();
}
}
http://stackoverflow.com/questions/10961714/how-to-properly-stop-the-thread-in-java – BackSlash