views:

41

answers:

1

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());
    } 

}
+3  A: 

You are sleeping for random number of seconds.

sleep((long)(Math.random()*1000)); // Because of this.

EDIT : To explain more, each time you run it sleeps for random number of seconds. So first thread can wake up five times before second thread. In another run, second thread can wake up two times before first thread, and so on.

fastcodejava
I see. So in the meantime the second thread starts to run and then again sleep executes.The first thread then continues from where it was before. Is that what is happening? Please explain
Maxood