Reputation: 29
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?
Upvotes: 3
Views: 1542
Reputation: 5754
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
Upvotes: 5
Reputation: 262484
If you need code to execute in a defined order on multiple threads, you need to add synchronization code between those threads.
Otherwise, the system is free to schedule execution in any order it sees fit.
Upvotes: 0
Reputation: 21883
Thread.start()
doesn't guarantee execution. It will just make the Thread state runnable and hand over to the Thread Scheduler. It is the Thread Scheduler which decides which thread to run when.
Upvotes: 2