Why the following Java code has different outputs each time?
        Posted  
        
            by Maxood
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Maxood
        
        
        
        Published on 2010-03-14T08:33:44Z
        Indexed on 
            2010/03/14
            8:45 UTC
        
        
        Read the original article
        Hit count: 699
        
threads
I don't know about threads in Java. I like to know what is happening in this code because each time it runs, it produces a different output:
public class TwoThreadsDemo{
    public static void main(String[] args)
    {
        new SimpleThread("Java Programmer").start();
        new SimpleThread("Java Programmer").start();
    }
}
class SimpleThread extends Thread{
    public SimpleThread(String str)
    {
      super(str);
    }
    public void run()
    {
        for (int i=0;i<10;i++)
        {
           System.out.println(i + " " + getName());  
            try
            {
                sleep((long)(Math.random()*1000));
            }
            catch(InterruptedException e)
            {
            }
        }
        System.out.println("Done!" + getName());
    } 
}
© Stack Overflow or respective owner