【发布时间】:2015-09-10 07:49:51
【问题描述】:
在下面的代码中,notifyAll() 被调用但不会重新激活其他线程。我得到的输出是
beta 等待收到通知的时间:1441870698303,activeWriters:1
alpha 等待收到通知的时间:1441870698303,activeWriters:1
-
delta notify all at time: 1441870698403, activeWriters: 0
公共类 Waiter 实现 Runnable{
private static int activeWriters; public Waiter(Message msg){ } @Override public void run() { beforeWrite(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } afterWrite(); } protected synchronized void beforeWrite(){ while (activeWriters > 0 ) { try { System.out.println(Thread.currentThread().getName() +" waiting to get notified at time: "+System.currentTimeMillis()+ ", activeWriters: " + activeWriters); wait(); System.out.println(Thread.currentThread().getName() +" waiting got notified at time: "+System.currentTimeMillis()+ ", activeWriters: " + activeWriters); } catch (InterruptedException e) { e.printStackTrace(); } } ++activeWriters; } protected synchronized void afterWrite(){ --activeWriters; System.out.println(Thread.currentThread().getName() +" notify all at time: "+System.currentTimeMillis() + ", activeWriters: " + activeWriters); notifyAll(); } } public class WaitNotifyTest { public static void main(String[] args) { Message msg = new Message("process it"); Waiter waiter1 = new Waiter(msg); Waiter waiter2 = new Waiter(msg); Waiter waiter3 = new Waiter(msg); new Thread(waiter1,"alpha").start(); new Thread(waiter2, "beta").start(); new Thread(waiter3, "delta").start(); } }
【问题讨论】:
标签: java multithreading concurrency wait