2016-12-07 66 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(); 
    } 
} 
相关问题