我只是想知道为什么它必须在第二个循环中加入线程
当编写如下代码时:
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);
}
}
}
输出为:
Thread-0:1
Thread-0:2
...
Thread-4:8
Thread-4:9
这意味着顺序打印出来。那么,有人知道原因吗?
非常感谢并致以最诚挚的问候。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将在开始下一个线程之前加入每个线程。
在任何一个时间点,只会有一个线程在运行,因为您已经等待前一个线程完成。
您需要在等待第一个线程完成之前启动所有线程。
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.
将 main 方法更改为:
基本上,thread.start() 将在后台启动线程并继续。然后,当您执行 thread.join() 时,执行将停止,直到线程完成。因此,在您的程序版本中,您启动每个线程,然后等待它完成,然后再启动下一个线程,从而顺序执行。
Change the main method to:
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.