开发者

Java - gracefully quit threads

I got a bunch of threads that perform calculations. They are "synchronized" using a CyclicBarrier. When any thread's run() method finishes, I want all other threads to exit as well once they call await() on the barrier the next time.

So far, everything I've tried either hangs at the await() calls or results in a broken barrier. Any tips?

EDIT: Here's the (basic) code:

public MyClass implements Runnable {
    public void run() {
        while (true) {
            if (someCondition) {
                // quit other threads when they call await()
                return;
  开发者_运维百科          }
            barrier.await();
    }
}


reset() will awaken all waiting threads with a thrown exception

you can then use the await as so

private static volatile boolean shouldStop=false;

public void run() {
    try{
        while (true) {
            if (someCondition) {
                // quit other threads when they call await()
                return;
            }
            try{
                if(shouldStop)return;
                barrier.await();
            }catch(BrokenBarrierException e){
                //someone stopped 
                return;
            }
       }
   }finally{
       shouldStop =true;
       barrier.reset();
   }
}

you can also call a method for the if(shouldStop) check


From the sounds of it you probably want a CountDownLatch. Assuming you know the number of threads/participants, you simply create one for that many and then when your thread is done count down and await the latch:

final int workers = …
final CountDownLatch latch = new CountDownLatch(workers);

void doSomething() throws InterruptedException {
  …
  latch.countDown();
  latch.await(); // blocks, throws InterruptedException
}

Compared to CyclicBarrier, CountDownLatch is not reusable, you only use it once. It does however separate the waiting and the releasing concerns, so you can for instance have another thread that allows the threads through.

All that said, if you do need a CyclicBarrier a slight variation on the above code should work:

final int workers = …
final CyclicBarrier barrier = new CyclicBarrier(workers);

void doSomething() throws InterruptedException, BrokenBarrierException {
  …
  latch.await(); // blocks, throws InterruptedException, BrokenBarrierException
}

however, if any thread is interrupted or barrier.reset() is called then barrier is broken and the exception is thrown.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜