等待多个线程完成

时间:2020-08-11 16:15:00

标签: java multithreading

我知道还有更多与此相关的帖子。但是我无法真正回答答案。夏天的炎热和主题都使它变得困难。所以我希望有人可以帮助我解决我的具体情况。

我想要的是以下内容:

static public <T> void update(Quad_Tree<T> qt) {


    Thread[] threads = new Thread[4];

    for (int i = 0; i < 4; i++) {

        final int index = i;

        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                update(qt.root.children[index]);
            }
        });

        threads[index] = thread;
        thread.start();
    }

    // What is a good way to know those threads are done?
    // ...

}




static public <T> void update(Quad_Tree_Node<T> qtn) {

    // my update function that does not need synchronized and is totally thread safe
}

我更喜欢不引入大量Java类的解决方案。而且我需要做很多挖掘工作才能知道他们在后台做什么。

我尝试了此方法,但是它不起作用:

 while (true) {
        int count = 0;
        if (!threads[0].isAlive()) count++;
        if (!threads[1].isAlive()) count++;
        if (!threads[2].isAlive()) count++;
        if (!threads[3].isAlive()) count++;
        if (count == 4) {
            break;
        }
    }

1 个答案:

答案 0 :(得分:-1)

以下代码将起作用:

while (threads[0].isAlive() ||
       threads[1].isAlive() ||
       threads[2].isAlive() ||
       threads[3].isAlive())