2013-08-22 58 views
4

我需要在这里解释。线程正在等待另一个线程

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

10个线程为WaiterThread创建并正在等待的单个FirstThread对象。之后FirstThread终止,所有WaiterThread重操旧业没有obj.notify()obj.notifyAll()被称为任何地方。

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

回答

6

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

此外,引用相同的文档:

建议应用程序不使用waitnotify,或notifyAllThread实例。

当然,同样的建议适用于Thread,这是你的代码做例子。

6

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

建议应用程序不使用的等待,通知,或notifyAll的对线程实例

+3

人们会怀疑我们坐在同一个房间:) –

+0

很高兴见到你:-) –

+0

当然,同样:) –

0

我修改的代码有点如下

主()方法保持相同

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()时会调用notifyAll(),但每个线程一次只能有一个锁。所以虽然每个线程都会收到通知,但一次只能执行一个线程。