Multithreading 为什么下面的Java代码每次都有不同的输出?

Multithreading 为什么下面的Java代码每次都有不同的输出?,multithreading,Multithreading,我不知道Java中的线程。我想知道这段代码中发生了什么,因为它每次运行时都会产生不同的输出: public class TwoThreadsDemo{ public static void main(String[] args) { new SimpleThread("Java Programmer").start(); new SimpleThread("Java Programmer").start(); } } class Simp

我不知道Java中的线程。我想知道这段代码中发生了什么,因为它每次运行时都会产生不同的输出:

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

}
公共类TwoThreadsDemo{
公共静态void main(字符串[]args)
{
新的SimpleThread(“Java程序员”).start();
新的SimpleThread(“Java程序员”).start();
}
}
类SimpleThread扩展线程{
公共SimpleThread(字符串str)
{
超级(str);
}
公开募捐
{

对于(inti=0;i,您睡眠的时间为随机秒数

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

编辑:为了进一步解释,每次运行它都会随机休眠几秒钟。因此,第一个线程可以在第二个线程之前唤醒五次。在另一次运行中,第二个线程可以在第一个线程之前唤醒两次,依此类推。

我明白了。因此,在此期间,第二个线程开始运行,然后再次执行休眠。第一个线程然后,线程从以前的位置继续运行。这就是正在发生的事情吗?请解释