日期:2014-05-20  浏览次数:20708 次

java线程并发 wait notify notifuAll 请大神给予解答
package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class NotifyVsNotifyAll {

public static void main(String[] args) throws Exception{

ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 5; i++){
exec.execute(new Task());
}
exec.execute(new Task2());
TimeUnit.SECONDS.sleep(1);
Task.blocker.prod();
System.out.println(" the end of the programs ! ");
}
}
class Blocker{
synchronized void waitingCall(){
try{
while(!Thread.interrupted()){
System.out.println(Thread.currentThread() + " is waiting !!!");
wait();
System.out.println(Thread.currentThread() + "has done!!!");
}
}catch(Exception exp){

}
}
synchronized void prod(){
System.out.println(Thread.currentThread() + " prod() !");
notify();
}
synchronized void prodAll(){
notifyAll();
}
}

class Task implements Runnable{
static Blocker blocker  = new Blocker();
@Override
public void run() {
// TODO Auto-generated method stub
blocker.waitingCall();
}
}

class Task2 implements Runnable{
static Blocker blocker  = new Blocker();
@Override
public void run() {
// TODO Auto-generated method stub
blocker.waitingCall();
}
}

/*output:
Thread[pool-1-thread-1,5,main] is waiting !!!
Thread[pool-1-thread-3,5,main] is waiting !!!
Thread[pool-1-thread-5,5,main] is waiting !!!
Thread[pool-1-thread-2,5,main] is waiting !!!
Thread[pool-1-thread-4,5,main] is waiting !!!
Thread[pool-1-thread-6,5,main] is waiting !!!
Thread[main,5,main] prod() !
 the end of the programs ! 
Thread[pool-1-thread-1,5,main]has done!!!
Thread[pool-1-thread-1,5,main] is waiting !!!
*/


这个是java编程思想上面的一个题目,我改了一下,我就是想请教一下大神,
为何结果是上面那样的,因为Task中的blocker只有一个,那么当一个线程
调用waitingCall()的时候,其他的线程应该就要等待了呀,为什么还会出现
Thread[pool-1-thread-3,5,main] is waiting !!!
Thread[pool-1-thread-5,5,main] is waiting !!!
Thread[pool-1-thread-2,5,main] is waiting !!!