2016-12-07 77 views

回答

1

是的,你可以做到以下幾點:

創建一個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(); 
    } 
} 
相關問題