Thread execution after .start() method

lev :

I am wondering what happens in the following scenario:

Two threads are created:

Thread t1 = new Thread();
Thread t2 = new Thread();

Assume these just print out a string, the threads then call the .start() method:

t1.start();
t2.start():

My question is why do these threads print in a seemingly random order each time? I know threads execute concurrently but would t1 not always finish before t2 due to the sequential execution of the main process?

kaan :

Calling start() on a Thread doesn't necessarily result in the thread running immediately after. It is possible for other things to happen in between your calling start() and the first line of your thread's run() method actually being run. And even once your run() is actually running, it's also possible that other things happen before, during, or after your run() method finishes.

In your question, you said: "assume these just print out a string" – here's an implementation of run() which does that:

public void run() {
    System.out.println("my name is: " + getName());
}

So it's possible that t1 starts to run first, but before it actually calls System.out.println, t2 is allowed to execute and runs to completion, then t1 is resumed.

If this kind of behavior won't work for your use case, you'll need to add some kind of concurrency protection to coordinate how and when your threads run.

UPDATE:

To illustrate the unpredictable sequence of thread execution, run this code a few times and observe the output:

public class Example {
    public static void main(String[] args) {
        for (int k = 0; k < 10; k++) {
            new TestThread(k).start();
        }
    }
}

class TestThread extends Thread {
    private final int k;

    TestThread(int k) {
        this.k = k;
    }

    @Override
    public void run() {
        System.out.print(k + " ");
    }
}

Here is the output from one of my local runs:

7 0 1 5 4 6 3 2 8 9 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306705&siteId=1