4

鉴于:

Executor executor = ...;
Phaser phaser = new Phaser(n);
for (int i=0; i<n; ++i)
{
  Runnable task = new Runnable()
  {
    public void run()
    {
      phaser.arriveAndDeregister();
      if (lastTask)
        doSomething(this);
    }
  }

  // run tasks using a thread-pool (order is not guaranteed)
  executor.submit(task);
}

我想知道我是否是最后一个要触发doSomething()的任务,这取决于任务的内部状态。我找到了 Phaser.onAdvance(int, int)但不清楚在这种情况下如何使用它。

4

2 回答 2

0

我想不出一种非常优雅的方法来解决这个问题,但是使用 ThreadLocal 和 onAdvance 可以提供帮助。

    final ThreadLocal<Boolean> isLast = new ThreadLocal<Boolean>() {
        public Boolean initialValue() {
            return false;
        }
    };
    final Phaser p = new Phaser(9) {
        public boolean onAdvance(int phase, int registeredParties) {
            isLast.set(true);
            return true;
        }
    };

然后

  public void run()
    {
      phaser.arriveAndDeregister();
      if (isLast.get())
        doSomething(this);
    }
于 2011-09-27T18:50:16.997 回答
0

由于您似乎事先知道您有多少任务,因此只需使用单独的AtomicInteger.

int n = 5;
ExecutorService executor = ...
final AtomicInteger count = new AtomicInteger (n);
final Phaser phaser = new Phaser (n);
for (int i = 0; i < n; ++i) {
    Runnable task = new Runnable () {
        public void run () {
            phaser.arriveAndDeregister ();
            if (count.decrementAndGet () == 0) {
                doSomething (this);
            }
        }
    };

    // run tasks using a thread-pool (order is not guaranteed)
    executor.submit (task);
}

或者,如果您需要在doSomething通知休眠方之前打电话,只需覆盖onAdvance并从那里进行。

final Phaser phaser = new Phaser (n) {
    protected boolean onAdvance(int phase, int registeredParties) {
        doSomething(this);

        return super.onAdvance(phase, registeredParties);
    }
};
于 2013-06-13T14:57:53.030 回答