如何在所有线程完成后立即执行某些操作?

时间:2012-02-29 01:56:52

标签: java multithreading synchronization

假设我想要运行n个线程,并且我希望在所有线程完成时输出一些内容。以下是我尝试过的方法:

//This uses a ThreadGroup called tGroup
while(tGroup.activeCount() > 0) {
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

接下来只是一个while循环和一个存储Threads的ArrayList

boolean alive = true;
int count = 0;
while (alive) {
    count = 0;
    for (int i = 0; i < numThreads; i++) {
        if (!threads.get(i).isAlive()) {
            count++;
        }
        if (count == numThreads) {
            alive = false;
            break;
        }
    }
}

3 个答案:

答案 0 :(得分:3)

遍历所有主题并join()每个主题。 join()将阻止任何未完成的线程,直到它完成。

答案 1 :(得分:2)

我认为您想要使用的是CountDownLatch,因为这是专为此类情况而构建的。每个工作线程在完成时都会通知锁存器,然后锁存器上调用await()的所有线程将保持操作直到倒计时完成。请查看我上面给出的API链接中的示例代码,看看它的使用方式和灵活性。

修改
哎呀,我想我发布这篇文章已经太晚了。但不管你接受了另一个答案,你还是要自己检查一下,因为它非常优雅且易于使用。

例如:

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchEg {
   public static void main(String[] args) {
      int threadCount = 8;
      CountDownLatch latch = new CountDownLatch(threadCount);
      System.out.println("Start all threads");
      for (int i = 0; i < threadCount; i++) {
         new Thread(new MyRunnable(latch, i)).start();
      }
      System.out.println("All threads started");
      try {
         latch.await();
      } catch (InterruptedException e) {}
      System.out.println("All threads finished");

   }
}

class MyRunnable implements Runnable {
   private CountDownLatch latch;
   private Random rand = new Random();
   private long delay;
   private int id;

   public MyRunnable(CountDownLatch latch, int id) {
      this.latch = latch;
      delay = (rand.nextInt(4) + 1) * 1000;
      this.id = id;
   }

   @Override
   public void run() {
      System.out.println("Start thread: " + id);
      try {
         Thread.sleep(delay);
      } catch (InterruptedException e) {}
      System.out.println("End thread: " + id);
      latch.countDown();
   }
}

答案 2 :(得分:0)

你不是这个意思:

boolean alive = true;
int count = 0;
while (alive) {
    count = 0;
    for (int i = 0; i < numThreads; i++) {
        if (!threads.get(i).isAlive()) {
            count++;
        }
    }
    if (count == numThreads) {
        alive = false;
    }
}