Reputation: 1097
class Name implements Runnable {
public void run() {
for (int x = 1; x <= 3; x++) {
System.out.println("Run by "
+ Thread.currentThread().getName()
+ ", x is " + x);
}
}
}
public class Threadtest {
public static void main(String [] args) {
// Make one Runnable
Name nr = new Name();
Thread one = new Thread(nr);
Thread two = new Thread(nr);
Thread three = new Thread(nr);
one.setName("A");
two.setName("B");
three.setName("C");
one.start();
two.start();
three.start();
}
}
The answer is different while compiling and running more then one time I don't know why? any idea.
Upvotes: 2
Views: 141
Reputation: 4340
one of them will start running first then the second and lastly the third . that is depend on thread scheduler on system
Upvotes: 1
Reputation: 1502736
It should show the same output, but potentially in a different order for each run.
You've got three independent threads: each will show three lines of output, in the obvious order - but there's no guarantee which thread will execute first, etc. In this particular case I don't believe you've got any side effects which would cause truly strange behaviour - just the normal ambiguity of which threads will run when. Note that on a multicore processor the threads are likely to be running simultaneously - the only synchronization is whatever happens within System.out.println
.
Upvotes: 7