-2

I know there are more posts about this. But I can't really wrap my head around the answers. Both the summer heat and the subject is making it hard. So I was hoping that someone can help me with my specific case.

What I want is the following:

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
}

I prefer a solution that does not introduce tons of java classes. And where I need to do a lot of digging to know what they are doing in the background.

I tried this, but it does not work:

 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;
        }
    }
clankill3r
  • 9,146
  • 20
  • 70
  • 126
  • 1
    Iterate over `threads`, call [`.join()`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Thread.html#join()) on each element: `for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } }`. After execution reaches end of this loop, all `threads` have finished. – Turing85 Aug 11 '20 at 16:17
  • Does this answer your question? [Java Wait for thread to finish](https://stackoverflow.com/questions/4691533/java-wait-for-thread-to-finish) – akuzminykh Aug 11 '20 at 16:19
  • @Turing85 - you should write that as an answer – user13784117 Aug 11 '20 at 16:31

1 Answers1

-1

Below code will work:

while (threads[0].isAlive() ||
       threads[1].isAlive() ||
       threads[2].isAlive() ||
       threads[3].isAlive())
Suman
  • 818
  • 6
  • 17