Click here to Skip to main content
15,881,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Why the following code does not give the same output when we compile it again and again?
C#
class A implements Runnable
{
    Thread t;
    String s;
    A(String st)
    {
        s=st;
        t=new Thread(this,s);
        System.out.println(s+" "+t);
        t.start();
    }
    
    public void run()
    {
        try
        {
            for(int i=5;i>0;i--)
            {
                System.out.println(i);
                Thread.sleep(4000);
            }
        }
        catch(InterruptedException e)
        {
            System.out.println(e);
        }
        System.out.println("In Run()");
    }
}
public class demo14 {
    public static void main(String args[])
    {
        A t1=new A("one");
        A t2=new A("two");
        A o3=new A("three");
        System.out.println("In main");
        
    }
}
Posted
Updated 23-Jun-11 4:31am
v2
Comments
CPallini 23-Jun-11 10:28am    
Because it is 'magic'!
Sandeep Mewara 23-Jun-11 10:33am    
Apart from magic, what do you mean by different output on re-compile?
Ashutosh_g 23-Jun-11 10:39am    
This code when we compile first time it gives the following output like this:-
one Thread[one,5,main]
two Thread[two,5,main]
three Thread[three,5,main]
In main
5
5
5
4
4
4
3
3
3
2
2
2
1
1
1
In Run()
In Run()
In Run()


When we compile it second time it gives following output :-

one Thread[one,5,main]
two Thread[two,5,main]
three Thread[three,5,main]
5
In main
5
5
4
4
4
3
3
3
2
2
2
1
1
1
In Run()
In Run()
In Run()

Ehy is the difference in the Thread output ?


1 solution

All the thread have the same priority, so it is up to the system when they run again. The actual order of thread execution is not guaranteed and is subject to allsorts of factors outside your control! There is a description here: http://journals.ecs.soton.ac.uk/java/tutorial/java/threads/priority.html[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Jun-11 14:35pm    
Sure. My 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900