user547453
user547453

Reputation: 1045

java multithreading - child thread does not start immediately

I am learning about MULTITHREADING in java and I want to know why in the following code, the child thread does not immediately run when the start method is executed to invoke the run method in the child thread?

Instead, after executing the start method, the main thread keeps executing its code and starts printing ".". Which it does three times and the control is taken over by the child thread. The child thread then executes its code one time and returns back to the main thread. Then main thread completes and then the child thread completes its execution as well.

I am unable to understand why this happens?

class MyThread implements Runnable {

    String thrdName;

    MyThread(String name) {
        thrdName = name;
    }

    public void run() {
        System.out.println(thrdName + " starting.");
        for (int count = 0; count < 10; count++) {
            System.out.println("In " + thrdName + ", count is " + count);
        }
    }
}

class UseThreads {

    public static void main(String args[]) {
        System.out.println("Main thread starting.");
        MyThread mt = new MyThread("Child #1");
        Thread newThrd = new Thread(mt);
        newThrd.start();
        for (int i = 0; i < 50; i++) {
            System.out.print(".");
        }
    }
}

Upvotes: 0

Views: 732

Answers (2)

user82238
user82238

Reputation:

The call to begin a thread is asychronous. It does not wait until the thread has started running before returning; it returns essentially immediately.

You can implement that behaviour yourself, with a bit of locking, such that your main thread pauses until the thread you have begun issues a signal of some kind, to indicate it has begun execution.

Upvotes: 2

Keppil
Keppil

Reputation: 46239

When you call start() on your thread, you get no guarantees on how fast it will start. This is up to the thread scheduler of your computer. If you run your code multiple times, you will likely get several different execution orders for your threads.

Upvotes: 4

Related Questions