是否在螺纹完成时发出通知?为什么此代码示例工作? [英] Is a notify signalled on thread finish? Why does this code sample work?

查看:195
本文介绍了是否在螺纹完成时发出通知?为什么此代码示例工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找某些谜题的线程,我不知道为什么下面一贯打印 999999

I am looking in some puzzles for threads and I can't figure out why the following consistently prints 999999:

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

没有 / code>在同一个锁(和虚假的唤醒似乎被忽略)。

如果一个线程完成了一个通知得到信号或某事?

如何来到<$

There is no notify on the same lock (and spurious wakeup seem to be ignored).
If a thread finishes does a notify get signalled or something?
How come main prints the result and not get "stuck" waiting?

推荐答案

在Javadoc for Java 7 Thread.join (长)

In the Javadoc for Java 7 Thread.join(long)


此实现使用this.wait调用的循环,调用this.isAlive。当线程终止时,调用this.notifyAll方法。建议应用程序不在Thread实例上使用wait,notify或notifyAll。

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

使用Thread直接这种方式被认为是不实际的。

Using a Thread directly this way is considered bad practical. Note: wait() could end for any number of reasons, possibly spuriously.

基于与@ Voo相关的解谜器评论。关键是你不应该使用Thread的内部行为,因为这更有可能导致混乱。

Based on a puzzler related to @Voo's comment. The point is you shouldn't play with the internal behaviour of Thread as this is more likely to lead to confusion.

public static String getName() {
    return "MyProgram";
}
public static void main(String... args) {
    new Thread() {
       public void run() {
           System.out.println("My program is " + getName());
        }
    }.start();
}

此程式列印什么?

这篇关于是否在螺纹完成时发出通知?为什么此代码示例工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆