Java - 防止 SwingWorker 中断

Java - Protect from interrupt SwingWorker

我需要中断 swingworkers,但如果线程是 运行 某个片段,它应该在那之后中断。像这样:

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);

我试过同步块,但不确定是不是行不通,还是我做错了。

有办法吗?谢谢!

您可以通过定期检查线程的标志来控制的任何方式。 所以在开始之前你可以检查标志或中断然后继续。

将标志设置为易变的,这样它对所有线程或 AtomicBoolean 都可见

 while (flag) {
       //do stuff here
     }

或者你可以使用中断来取消任务。

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

   }