2

在我看来,这个程序的输出只能是

Hello 0 1 2 3 4 Yes

但答案列出

0 1 2 3 4 Hello Yes

作为一个可能的答案。我的问题是当测试进入睡眠状态时,不应该 main 是唯一进入运行状态的其他线程,这样 Hello 应该总是首先打印吗?

public class Lean   
{
    public static void main(String args[]) throws Exception 
    {
        Test test = new Test();
        test.start();
        System.out.print("Hello ");
        test.join();
        System.out.print("Yes");
    }
}

class Test extends Thread
{
    public void run()
    {
        try
        {
            Thread.sleep(2000);
        } catch (InterruptedException e)
        {}
        for (int counter=0; counter<5 ; counter++)
        {
            System.out.print(counter + " ");
            }
    }
}
4

2 回答 2

3

线程运行顺序是不确定的......可能是睡眠将允许另一个进程运行,而您的测试线程是在执行返回到您的进程时恢复的线程......睡眠不是一个好的同步方法

如果您确实想开始控制事情的完成顺序,那么您需要查看 Mutex 之类的东西......

于 2011-05-10T07:13:09.187 回答
1

大多数时候它会做你期望的事情。但是,即使线程休眠 2 秒,main 也没有机会运行,这种可能性非常小。

关键是:Thread.sleep不会强制调度程序运行另一个线程(尽管它会给它一个很好的提示)。

于 2011-05-10T07:13:17.387 回答