Java 在这个程序中,为什么线程[Two,5,main]出现在1:5之前?

Java 在这个程序中,为什么线程[Two,5,main]出现在1:5之前?,java,multithreading,Java,Multithreading,输出: package javaapplication18; class Alistair_Therein implements Runnable{ String name Thread t; Alistair_Therein(String threadname){ name = threadname; t = new Thread(this, name); System.out.println("New thread:"

输出:

package javaapplication18;
class Alistair_Therein implements Runnable{
String name
     Thread t;
     Alistair_Therein(String threadname){
         name = threadname;
         t = new Thread(this, name);
         System.out.println("New thread:" + t);
         t.start();
     }
     public void run(){
         try{
             for(int i=5; i>0; i--){
                 System.out.println(name " : " + i);
                 Thread.sleep(1000);
             }
         }catch(InterruptedException e) {
             System.out.println(name + "interrupted");
         }
         System.out.println(name + "exiting");
     }


 }

public class Main {


    public static void main(String[] args) {
        new Alistair_Therein("One");
        new Alistair_Therein("Two");
        new Alistair_Therein("Three");
        try{

                Thread.sleep(10000);
            }
        }catch(InterruptedException e){
            System.out.println("Main Thread interrupted");
        }
        System.out.println("Main thread exiting.");
    }

}

为什么线程[Two,5,main]出现在1:5之前?

除非使用同步结构,否则无法保证在不同线程中看到事件发生的顺序


[在这个特定的例子中,我猜启动线程所涉及的开销远远大于启动新对象所涉及的开销,因此新对象创建获胜。]

线程被设计为并行和独立运行,这就是关键所在。独立线程的输出可以以任何顺序进行。

注意,start并不意味着新创建的线程的Runnable.run方法中的代码将在该时刻启动。它只是将线程置于可运行状态,并让调度程序决定它实际运行的时间

在任何新创建的线程执行代码之前,所有3个线程对象的构造很可能会一次性运行


还请注意,打印到System.out或System.err会强制执行同步,这很容易影响测试结果。

这是因为您正在打印线程。线程[One,5,main]会打印,因为这些是线程的详细信息。 这里有一个指出线程名称。 5这里指出线程优先级编号。 main代表线程组。 如果你评论这行

//System.out.println新线程:+t


线程[1,5,main]它不会出现。

如果不使用同步,睡眠有什么意义?作者说,让主线程最后退出是很困难的?@Abhay:在细粒度级别上,两个线程将竞相完成。当然,从粗粒度的角度来看,10秒的睡眠总是在5次1秒的睡眠之后结束。但是不要试图用睡眠来代替正确的同步。嗯,ok听起来很合理。如果你能找到一些实质性的支持,那就太好了up@AbhaySaini即使没有显式同步,我们几乎可以完全确定生成三个线程并使每个线程计数为5所需的时间将少于睡眠持续时间我怀疑Thread.sleep需要毫秒参数,那就是10秒。但是有35秒的睡眠功能吗?这难道不是出自赫伯特·席尔德的一本书吗?他使用睡眠,所以你可以看到交错输出。如果没有睡眠,第一个线程可以在第二个线程启动之前完成,您可能看不到任何并发运行的线程。 New Thread: Thread[One, 5, main] New Thread: Thread[Two, 5, main] New Thread: Thread[Three, 5, main] One: 5 Two: 5 Three: 5 One: 4 Two: 4 Three: 4 One: 3 Two: 3 Three: 3 One: 2 Two: 2 Three: 2 One: 1 Two: 1 Three: 1 One exiting. Two exiting. Three exiting. Main thread exiting.