1

我一直在为我的 O/SCJP 考试做一些练习。考虑以下代码:

public class Cruiser implements Runnable {
    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(new Cruiser());
        a.start();

        System.out.print("Begin");
        a.join();
        System.out.print("End");
    }

    public void run() {
        System.out.print("Run");
    }
}

来源:http ://scjptest.com/mock-test.xhtml

该站点声明输出(他们模拟问题的答案)将是BeginRunEnd,并且在正常运行课程时,这正是输出的内容。

但是,调试时输出为RunBeginEnd.

公平地说,在正常执行下,输出将始终BeginRunEnd或者这会根据其他因素而变化(例如新线程类的重量/启动线程后加入它需要多长时间)?

你会说这是一个公平/准确的考试问题吗?

4

3 回答 3

3

我认为 BeginRunEnd 比 RunBeginEnd 更有可能(我希望实际启动新线程的行为在它到达run方法之前需要一段时间,并且第一个线程在它用完它的时间片之前到达打印在大多数情况下),但是在编程时假设它是完全不正确的。

您应该将两个线程视为完全独立start,直到它们再次与join调用显式绑定在一起。从逻辑上讲,新线程可以在主线程打印“开始”之前一直运行到完成。

对我来说,这似乎是一个糟糕的问题。

于 2011-07-29T14:10:59.583 回答
2

这是一个垃圾问题。没有同步,结果是不确定的。

这真的是 bofa fida SCJP 问题,还是只是某个试图销售 SCJP 培训的网站编造的问题?如果是后者,那么我会像瘟疫一样避开那个网站。

于 2011-07-29T14:53:14.413 回答
1

这可能与平台相关,但显示顺序可以更改。

public class Cruiser implements Runnable {
    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(new Cruiser());
        a.setPriority(Thread.MAX_PRIORITY);
        a.start();

        // Thread.sleep(1);

        System.out.print("Begin");
        a.join();
        System.out.print("End");
    }

    public void run() {
        System.out.print("Run");
    }
}

我第一次运行它时打印。

RunBeginEnd

但是在那之后它主要是 BeginRunEnd

如果线程停止,即使是 1 毫秒,它几乎每次都会产生 RunBeginEnd。

于 2011-07-29T14:20:20.333 回答