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.
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.