线程等待另一个线程

时间:2013-08-22 08:35:45

标签: java multithreading

我需要在这里解释一下。

 public static void main(String[] args) {
    FirstThread obj = new FirstThread();
    for (int i = 1; i <= 10; i++) {
      new WaiterThread(obj).start();
    }
    obj.start();
  }

public class FirstThread extends Thread {
  @Override
  public void run() {
    // Do something
  }
}


public class WaiterThread extends Thread {
  Object obj;

  WaiterThread(Object obj) {
    this.obj = obj;
  }

  @Override
  public void run() {
    synchronized (obj) {
           obj.wait();
    }
  }
}

WaiterThread 创建了10个线程,并且正在等待单个 FirstThread 对象。 FirstThread 终止后,所有 WaiterThread 在没有调用 obj.notify() obj.notifyAll()的情况下恢复任何地方。

这是否意味着 WaiterThread 停止等待 FirstThread 因为它被终止了?

3 个答案:

答案 0 :(得分:6)

根据the documentation of the Thread class,一个垂死的线程会在代表它的实例上调用notifyAll

此外,引用相同的文档:

  

建议应用程序不要在wait个实例上使用notifynotifyAllThread

当然,相同的建议适用于Thread 子类的实例,这正是您的代码所做的。

答案 1 :(得分:6)

这是一个副作用,当一个线程终止时,它会调用this.notifyAll()(如Thread.join()的javadoc中所述)。同样的javadoc也提出了以下建议:

  

建议应用程序不在线程实例上使用wait,notify或notifyAll

答案 2 :(得分:0)

我修改了一下代码,如下所示

main()方法保持不变

 public static void main(String[] args) {
    FirstThread obj = new FirstThread();
    for (int i = 1; i <= 10; i++) {
      new WaiterThread(obj).start();
    }
    obj.start();
  }

更改如下

class WaiterThread extends Thread {
    Object obj;

    WaiterThread(Object obj) {
        this.obj = obj;
    }

    @Override
    public void run() {
        synchronized (obj) {
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread " + this.getId() + "started");
        }
        System.out.println("Out of sync block by " + this.getId());
    }
}

我得到的输出是

FirstThread Started
Thread 19started
Out of sync block by 19
Thread 18started
Out of sync block by 18
Thread 17started
Out of sync block by 17
Thread 16started
Out of sync block by 16
Thread 15started
Out of sync block by 15
Thread 14started
Out of sync block by 14
Thread 13started
Out of sync block by 13
Thread 12started
Out of sync block by 12
Thread 11started
Out of sync block by 11
Thread 10started
Out of sync block by 10

所以你有答案。它们不是同时启动的!在死亡时,FirstThread调用notifyAll(),除了每个线程一次只能锁定一个时,它会通知所有线程。因此,虽然每个线程都被通知,但一次只执行一个线程。