繁体   English   中英

阻止EDT,直到executorservice完成所有任务

[英]Block EDT till executorservice completes all task

在我的应用程序中,我有两个jtextpanes,我有一个包含很少任务的executorservice instacne。 我想确保在执行任何jtextpanes的FocusListener focusGained方法之前,executorservice实例中的所有任务都已完成。 当调用focusLost方法时,我还会向executorservice添加更多任务。

top.addFocusListener(new FocusListener()
{

  public void focusLost(FocusEvent e)
  {

    if (ecaViewControl.isInitialized())
    {
      stopRecording();
      executor.execute(new Runnable()
      {

        public void run()
        {
          ecaViewControl.save(top);

        }
      });

      executor.execute(new Runnable()
      {
        public void run()
        {
          ecaViewControl.closeDocument();

        }
      });

   }

  }

   public void focusGained(FocusEvent e)
   {
   //Need to have completed all the task in executor service before EDT executes the code in here

   });

}

如果您知道要完成的任务数,请考虑使用CountDownLatch

因此您的代码可能如下所示:

public void run() {
    try {
    // do something here
    } finally {
       latch.countDown()
    }
}

然后在代码中,您正在等待任务完成-只需等待闩锁即可:

latch.await();

或者,如果您可能没有执行者,则可以使用CompletionService

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM