Reputation: 632
Using the following code:
package myapp;
class Runner extends Thread {
public void run(){
for(int i = 0; i < 11; i++){
System.out.println("Hello " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Class1 {
public static void main(String[] args){
Runner t1 = new Runner();
t1.start();
Runner t2 = new Runner();
t2.start();
}
}
I get the following output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
Whereas my output should be as follows:
Hello 0
Hello 0
Hello 1
Hello 1
Hello 2
Hello 2
Hello 3
Hello 3
Hello 4
Hello 4
Hello 5
Hello 5
Hello 6
Hello 6
Hello 7
Hello 7
Hello 8
Hello 8
Hello 9
Hello 9
Hello 10
Hello 10
What's going wrong? I'm using Eclipse Standard/SDK Version: Kepler Release
Build id: 20130614-0229 , jre7u25 and jdk7u25.
Upvotes: 1
Views: 246
Reputation: 200148
This is your problem:
for(int i = 0; i < 11; i++){
System.out.println("Hello " + i);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You first run through the whole loop and only then sleep. Move the sleep inside the for-loop and see what happens.
Upvotes: 4
Reputation: 6622
1st output is correct, and what you are expecting is also correct. probability is 1 out of a million try.
While there are multiple threads, you can not pridict of getting any particular thread a chance to run. once dispatched to jvm (or CPU in case of native program), its upto jvm how & when it should run what thread.
1st out put is correct bcz, the code is so small that even before the thread requires switching, it has completed its task. thats why the output is not intervened. May be you can give it a try for bigger number of iteration, say >10000
so that you can understand this concept. or may you can try running the code number of times. you will(might) get a different output from the same code.
Ps: keeping the sleep
as the last instruction, has really no effect, since thread has almost finished its life, and you are just making it wait to die.
Upvotes: 2
Reputation: 117589
If the 2 threads have the same priority, then the order of execution is not guaranteed (running the same program twice might produce different results) and it depends on the hosted operating system as it is its job to dispatch the CPU between the threads.
Upvotes: 1