ayoo.dev
ayoo.dev

Reputation: 13

Question regards to Java Thread join() method

I was coding my assignment for Parallel Computing class and found this question.

For this assignment, the program suppose to get an integer input from the user to define how many Threads are they want to run. Then the program will create N amount of threads to run concurrently.

The following is a pseudo code that didn't work concurrently.

        for(int i = 0; i < N; i ++ ) {
            threads[i] = new MyThread();
            threads[i].start();
            threads[i].join();
        }

However, Once I change it to...

        for(int i = 0; i < N; i ++ ) {
            threads[i] = new MyThread();
            threads[i].start();
        }
        for(int i = 0; i < N; i ++ ) {
            threads[i].join();
        }

the program started working concurrently. Java API only states that join() will wait for the thread to die. So, it didn't help me understand why my code behaves like that. Can somebody explain to me why having join() method in a separate for-loop makes the program run concurrently?

Upvotes: 1

Views: 72

Answers (1)

Shadov
Shadov

Reputation: 5592

Simple:

  1. Create thread
  2. Start thread
  3. Wait for thread to end
  4. Go back to step 1

vs.

  1. Create thread
  2. Start thread
  3. Go back to step 1
  4. After 10 iterations: wait for each thread to end

How could the first version behave concurrently? Before you start a second thread you are waiting for the first one to finish, always having only 1 thread (+main thread) running.

Upvotes: 4

Related Questions