开发者

Why the following Java code has different outputs each time?

开发者 https://www.devze.com 2022-12-22 17:39 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号