1

In my application i have two jtextpanes and i have a executorservice instacne which contains few task. I want to assure that all the task in the executorservice instance are completed before executing the FocusListener focusGained method of any jtextpanes. Also i add some more task to the executorservice when focusLost method is called.

Code

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

   });

}
4

1 回答 1

1

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

所以你的代码可能看起来像:

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

然后在您等待任务完成的代码中 - 只需等待闩锁:

latch.await();

或者,如果您可能没有执行人,请改用CompletionService 。

于 2012-09-17T13:46:19.780 回答