Java - 防止中断SwingWorker

时间:2017-06-06 12:41:10

标签: java multithreading 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);

我已经尝试过同步块,但不确定这是否有效或我只是做错了。

有办法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

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

将标志设置为volatile,以便所有线程或AtomicBoolean

可见
 while (flag) {
       //do stuff here
     }

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

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

   }