在线程对象上同步

时间:2013-06-02 18:39:48

标签: java multithreading scjp

来自Niko's java blog

  

这些类在同一个文件中定义。什么是输出? (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。我理解当一个Thread完成它的run()方法时,它会终止并随之释放Thread释放的所有锁。但是,在本练习中,它使用Thread对象作为锁,不应该将它视为普通对象吗?我的意思是锁不是由线程thread拥有,而是由主线程拥有。

1 个答案:

答案 0 :(得分:5)

此代码依赖于Java 7之前未记录的实现细节,现在(在documentation of the join() method中),但使用以下单词:

  

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

所以我不知道这个问题在哪里被提出,但它真的测试你是否知道线程的隐藏角落,你永远不应该在任何理智的程序中使用。

相关问题