【发布时间】:2014-10-07 19:27:04
【问题描述】:
class Lock implements Runnable{
int i=0;
public synchronized void run(){
for(i=0;i<10;i++){
if(Thread.currentThread().getName().equals("t1") && i == 5)
{try { this.wait();} catch(InterruptedException ie){}}
System.out.print(Thread.currentThread().getName()+" ");
if(Thread.currentThread().getName().equals("t3") && i == 9)
this.notifyAll();
}
}
}
public class ThreadLock {
public static void main(String[] args){
Lock l = new Lock();
Thread t1 = new Thread(l);
Thread t2 = new Thread(l);
Thread t3 = new Thread(l);
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}
输出是: t1 t1 t1 t1 t1 t3 t3 t3 t3 t3 t3 t3 t3 t3 t3 t1 t2 t2 t2 t2 t2 t2 t2 t2 t2 t2
调用 notifyAll 方法后,t1 未打印全部 10 次。 我运行了很多次,但每次 t1 只打印 6 次。 为什么 t1 没有全部打印 10 次? 请尽快回复
【问题讨论】:
-
即使您已将
i更改为局部变量,该程序也不能保证始终打印“t1”十次。理论上,t3 线程有可能在 t1 任务调用wait()之前完成其任务并调用notifyAll()。如果发生这种情况,wait()调用将永远不会返回。
标签: java multithreading wait synchronized notify