2017-06-06 49 views
0

我需要中断swingworkers,但是如果线程正在运行某个片段,那么应该在此之后中断。事情是这样的:Java - 保护中断SwingWorker

public class worker extends SwingWorker<Integer, String>{ 
    //(...) constructors and everything else 

    protected Integer doInBackground() throws Exception{ 
     //Code that can be interrupted 
     while(true){ 
      //(...) more code that can be interrupted 

      //This shouldn't be interrupted, has to wait till the loop ends 
      for(int i=0; i<10; i++){ 

      //(...) more code that can be interrupted 
     }    
    } 
} 

中断工作者有:

Worker worker = new Worker(); 
worker.execute(); 
worker.cancel(true); 

我已经试过同步块,但如果不工作,或者我只是在做它没有错肯定。

有没有办法?谢谢!

+0

正如[本答案](https://stackoverflow.com/a/671053/4756299)中所述,您不会中断某个线程。以受控方式结束线程。 –

回答

0

任何方式,你可以控制一个标志,将定期检查线程。 因此,在开始之前,您可以检查标志或中断,然后继续。

挥发性

化妆标志,这样它将是所有线程或的AtomicBoolean

while (flag) { 
     //do stuff here 
    } 

可见,也可以使用中断取消任务。

try { 
     while(!Thread.currentThread().isInterrupted()) { 
     // ... 
     } 
    } catch (InterruptedException consumed) 

    }