Search code examples
javamultithreadingrunnable

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");
    }
}

Solution

  • 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(). When your program reach t.start() another thread will run and the main thread of your application will continue. 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"); you will see mix of both prints. For more information about java threads please visit here.