为什么线程不等待notify()? [英] Why doesn't thread wait for notify()?

查看:121
本文介绍了为什么线程不等待notify()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么线程不等待 notify()?线程启动,然后进入等待池,但它继续执行之后的那一刻。

  public class JavaApplication2 {
public static void main(String [] args){
ThreadB b = new ThreadB();
synchronized(b){
b.start();
try {
System.out.println(1);
b.wait();
} catch(InterruptedException e){}
System.out.println(Total is:+ b.total);
}
}
}
类ThreadB extends Thread {
int total;
@Override
public void run(){
synchronized(this){
total + = 1;
// notify();
}
}
}


解决方案>

您正在同步线程对象本身,这是错误的用法。发生的是,死亡的线程总是在它的线程对象上调用 notify Thread.join 依赖于此。因此,很清楚为什么你在这里有和没有你自己的通知一样的行为。



解决方案:use用于线程协调的单独对象;这是标准做法。


Why doesn't thread wait for notify()? The thread starts and then goes to the waiting pool, but it proceeds to execute after that moment.

public class JavaApplication2 {
    public static void main(String [] args) {
       ThreadB b = new ThreadB();
       synchronized(b) {
           b.start();
           try {
              System.out.println("1");
              b.wait();
         } catch (InterruptedException e) {}
          System.out.println("Total is: " + b.total);
       }
     }
 }
  class ThreadB extends Thread {   
    int total;
      @Override
    public void run() {
        synchronized(this) {
            total += 1;
            //notify();
       }
    }
 }

解决方案

You are synchronizing on the thread object itself, which is wrong usage. What happens is that the dying thread-of-execution always calls notify on its Thread object: Thread.join relies on this. Therefore it is clear why you get the same behavior with and without your own notify in there.

Solution: use a separate object for thread coordination; this is the standard practice.

这篇关于为什么线程不等待notify()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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