在编写如下代码时:
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这意味着顺序打印输出。那么,有人知道原因吗?
非常感谢并致以最良好的问候。
发布于 2011-09-18 23:27:43
在启动下一个线程之前,您要加入每个线程。
在任何单个时间点,将只有一个线程在运行,因为您已经等待前一个线程完成。
在等待第一个线程完成之前,您需要启动所有线程。
发布于 2011-09-18 23:37:19
将main方法更改为:
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;
}
}基本上,thread.start()将在后台启动线程并继续执行。然后,当您执行thread.join()时,执行将停止,直到线程结束。因此,在您的程序版本中,您先启动每个线程,然后等待它完成,然后再启动下一个线程,因此是顺序执行。
https://stackoverflow.com/questions/7462443
复制相似问题