Why the following Java code has different outputs each time?
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 Pr开发者_开发知识库ogrammer").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());
}
}
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.
精彩评论