【问题标题】:Java - Protect from interrupt SwingWorkerJava - 防止中断 SwingWorker
【发布时间】:2017-06-06 12:41:10
【问题描述】:

我需要中断 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);

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

有办法吗?谢谢!

【问题讨论】:

  • this answer 中所述,您不会中断线程。您以受控方式结束线程。

标签: java multithreading swingworker


【解决方案1】:

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

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

 while (flag) {
       //do stuff here
     }

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

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

   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多