2

来自Niko 的 Java 博客

这些类在同一个文件中定义。输出是什么?(1个正确答案)

class Job extends Thread {
    private Integer number = 0;
    public void run() {
        for (int i = 1; i < 1000000; i++) {
            number++;
        }
    }
    public Integer getNumber() {
        return number;
    }
}
public class Test {
    public static void main(String[] args) 
    throws InterruptedException {
        Job thread = new Job();
        thread.start();
        synchronized (thread) {
            thread.wait();
        }
        System.out.println(thread.getNumber());
    }
}
  • 它打印 0。
  • 它打印 999999。
  • 不保证输出为上述任何一种。

输出是999999。我知道当一个线程完成它的run()方法时,它会终止,并且线程的所有锁都会被释放。但是,在这个练习中,它使用 Thread 对象作为锁,不应该将其视为普通对象吗?我的意思是它不是由线程拥有的锁,thread而是由主线程拥有的。

4

1 回答 1

5

这段代码依赖于在 Java 7 之前没有记录的实现细节,现在是(在方法的文档中join()),但有以下文字:

当线程终止时,将调用 this.notifyAll 方法。建议应用程序不要在 Thread 实例上使用 wait、notify 或 notifyAll。

所以我不知道这个问题在哪里被问到,但它确实测试了你是否知道线程的隐藏角落情况,你不应该在任何理智的程序中使用。

于 2013-06-02T18:47:32.973 回答