Eric_Chen
Eric_Chen

Reputation: 227

I just wonder why it have to join threads in the second loop

When writing code like:

public class TestBasic {

    public static void print(Object o){
        System.out.println(o);
    }

    public static void main(String...strings) throws InterruptedException {
        Thread[] threads = new Thread[5];
        for(int i=0;i<5;i++){
            Thread thread = new Thread(new LittleRunner());
            thread.start();
            thread.join();
        }
    }

}

class LittleRunner implements Runnable{
    public void run() {
        for(int i=1;i<10;i++){
            TestBasic.print(Thread.currentThread().getName()+":"+i);
        }
    }
}

And the output is:

Thread-0:1
Thread-0:2
...
Thread-4:8
Thread-4:9

Which means sequentially printing out. So, does somebody know the reason?

Thanks a lot and Best regards.

Upvotes: 1

Views: 121

Answers (2)

Hari Menon
Hari Menon

Reputation: 35405

Change the main method to:

public static void main(String...strings) throws InterruptedException {
    Thread[] threads = new Thread[5];
    for(int i=0;i<5;i++){
        threads[i] = new Thread(new LittleRunner());
        threads[i].start();            
    }
    for(int i=0;i<5;i++){
        threads[i].join;            
    }
}

Basically, thread.start() will start the thread in background and move on. Then, when you do a thread.join(), the execution will stop until thread is finished. So, in your version of the program, you were starting each thread and then waiting for it to finish before starting the next thread, hence the sequential execution.

Upvotes: 1

SLaks
SLaks

Reputation: 887479

You're joining each thread before starting the next thread.
At any single point in time, there will only be one thread running, because you already waited for the previous thread to finish.

You need to start all of the threads before waiting for the first one to finish.

Upvotes: 2

Related Questions