开发者

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

开发者 https://www.devze.com 2023-04-05 12:05 出处:网络
When writing code like: public class TestBasic { public static void print(Object o){ System.out.println(o);

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开发者_StackOverflow社区 somebody know the reason?

Thanks a lot and Best regards.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消