i ran a code 10 times
on windows cmd line
and every time
i got same output
i ran the same code
on ideone ,10 times
and each time i got same output
as
My questions are :
according to my code child thread must sleep for 500ms
and main thread for 1000ms
so i think that after main thread runs once
, child thread runs twice
but in cmd output
, child ran 3 times
once and 1 time
other time. why?
output is different on ideone
and cmd
?
here is my code
class newthread extends Thread {
newthread() {
super("demo thread");
System.out.println("child thread:"+this);
start();}
public void run(){
try{
for(int i=5;i>0;i--) {
System.out.println("child thread:"+i);
Thread.sleep(500); }
}
catch(InterruptedException e){
System.out.println("child thread interrupted");}
System.out.println("child thread exiting");
}
}
class exthr{
public static void main(String args[]){
new newthread();
try{
for(int i=5;i>0;i--) {
System.out.println("main thread:"+i);
Thread.sleep(1000); }
}
catch(InterruptedException e){
System.out.println("main thread interrupted "); }
System.out.println("main thread exiting");
}
}
There are several reasons of such a difference:
sleep
. This basically deactivates thread for a while, but there are no guarantees that it will awake immediately. If you want particular order you should use synchronization primitives like mutexes and condition variables. So main sleeps for 1000 ms., and child sleeps twice for 500 ms. They should thus write to System.out
approximately at the same time.
Sometimes the main thread comes before, and sometimes after. That depends on the precision of the clock, on the other threads running, on the choices of the thread scheduler, on whether the threads sleep exactly for the time they were told to sleep or a bit more, on the time elapsed between the main thread starting the child thread and the time the thread actually starts running, etc.
You can't expect a strict sequence of events unless you correctly synchronize the threads to make them wait for each other.
You seem to assume that your program will resume immediately after timer runs out. This is not neccessarily the case on any machine, unless you are on a realtime system with control of all processes and priorities. It would be likely, though, that on a machine with moderate load, the behaviour would be like the behaviour exhibited by ideone. Admittedly, it is odd that your windows machine generates the same output allways, but it does not change the fact that the only guarantee you have is that your thread will sleep for AT LEAST the time you specify, not AT MOST. You could include a timestamp in your output to verify this, if you want to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.