简体   繁体   English

Runnable和Thread对象的打印顺序

[英]Print Order for Runnable and Thread object

It prints out "main thread" first and then prints out "child thread". 它先打印出“主线程”,然后再打印出“子线程”。 Why not "child thread" first? 为什么不首先使用“子线程”? Can anyone explain this? 谁能解释一下? Thank you. 谢谢。

public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println("child thread");
            }
        }
    });

    t.start();

    for (int i = 0; i < 10; i++) {
        System.out.println("main thread");
    }
}

Let me explain your code. 让我解释一下您的代码。

Thread t = new Thread(new Runnable() {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("child thread");
        }
    }
});

In this part you are defining a thread. 在这一部分中,您将定义一个线程。 This is just a definition and nothing will happen until t.start() . 这只是一个定义,直到t.start()都不会发生。 When your program reach t.start() another thread will run and the main thread of your application will continue. 当程序到达t.start()将运行另一个线程,并且应用程序的主线程将继续。 Probably until the thread initiation your main thread will print multile "main thread"s and when your thread reach to the System.out.println("child thread"); 大概在线程启动之前,您的主线程将打印多个“主线程”,并且当您的线程到达System.out.println("child thread"); you will see mix of both prints. 您会看到两种打印的混合。 For more information about java threads please visit here . 有关Java线程的更多信息,请访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM