Controlling Task execution order with ExecutorService

前端 未结 8 1951
一生所求
一生所求 2020-12-02 14:30

I have a process which delegates asynch tasks to a pool of threads. I need to ensure that certain tasks are executed in order. So for example

Tasks arrive in order<

8条回答
  •  离开以前
    2020-12-02 14:56

    When you submit a Runnable or Callable to an ExecutorService you receive a Future in return. Have the threads that depend on a1 be passed a1's Future and call Future.get(). This will block until the thread completes.

    So:

    ExecutorService exec = Executor.newFixedThreadPool(5);
    Runnable a1 = ...
    final Future f1 = exec.submit(a1);
    Runnable a2 = new Runnable() {
      @Override
      public void run() {
        f1.get();
        ... // do stuff
      }
    }
    exec.submit(a2);
    

    and so on.

提交回复
热议问题