无法预测所有线程何时完成执行

时间:2016-08-08 12:06:21

标签: java multithreading

这是我的代码

package pe.entel.ftp;

public class Myclass implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        Myclass runnable = new Myclass();
        ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

        for (int i = 0; i < 100; i++) {
            Thread t1 = new Thread(tg1, runnable, i + "");
            t1.start();
            System.out.println("Thread Group Name: " + tg1.getName());

        }
        while (tg1.isDestroyed()) {
            System.out.println("yes success");
        }

        System.out.println("completed");

    }
}

而我的o / p部分是

  Thread Group Name: Parent ThreadGroup
  Thread Group Name: Parent ThreadGroup
  Thread Group Name: Parent ThreadGroup
  Thread Group Name: Parent ThreadGroup
  Thread Group Name: Parent ThreadGroup
 completed
 84 
 86
 88
 90
 92
 94
 96
 98
 95
 97
 99

这里我无法预测线程组究竟何时完成执行。即使是用于检查线程组是否被销毁的while循环也无法正常工作。即使在打印完成后,一些线程正在执行。

2 个答案:

答案 0 :(得分:1)

ThreadGroup未完成执行。如果你想等待所有线程完成,你必须收集它们并等待所有线程:

List<Thread> allThreads = new ArrayList<>();

for (int i = 0; i < 100; i++) {
  Thread t1 = new Thread(tg1, runnable, i + "");
        t1.start();
   allThreads.add(t1);  
}

allThreads.forEach(Thread::join);

ThreadGroups的存在时间长于它们包含的线程,您可能希望在到目前为止所有线程完成之后将新线程添加到ThreadGroup。它们只是将线程分组,而不是控制它们。

答案 1 :(得分:0)

  

我无法预测确切的线程组何时完成执行

另一种方法是使用ExecutorService线程池而不是自己分叉线程:

ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
    threadPool.submit(new Myclass());
}
// shutdown the pool after the last runnable has been submitted
threadPool.shutdown();
// wait for all of the jobs to finish
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

您还可以使用Executors.newFixedThreadPool(#)仅分叉一定数量的线程来限制并发操作的数量。