java吧 关注:1,277,870贴子:12,796,020
  • 3回复贴,共1

问个问题,关于notify的用法。

只看楼主收藏回复

notify不是唤起一个等待的线程吗??
为什么我的这个程序有一个线程被唤起之后就直接退掉了。
class ThreadRun implements Runnable{
private boolean flag=true;
public synchronized void run(){
while(flag){
try{
System.out.println(" i'll sleep!!....");
//放弃线程
this.wait();
}catch(InterruptedException e){
System.out.println("exception output");
//修改运行条件
this.flag=false;
}
System.out.println("so what??");
}
//唤醒一个线程
this.notify();
}
public void change(){
//this.notifyAll();
this.flag=false;
}
}
public class Main{
public static void main(String[] args){
ThreadRun example = new ThreadRun();
Thread t1 = new Thread(example);
Thread t2 = new Thread(example);
Thread t3 = new Thread(example);
t1.start();
t2.start();
t3.start();
int i=0;
while(true){
if(i++<60){
System.out.println(Thread.currentThread().getName());
}else{
System.out.println("end............");
//example.change();
//清除t1线程的中断状态,问题就在这里,只是清除了t1的中断状态,t1执行后清除掉运行的条件时对的,但是之后t1执行的notify只可能唤醒一个线程,也就是t2和t3中的一个,而程序应该还有一个线程在等待,但为什么程序直接就退出了??
请前辈们指教。小鸟感激不尽~~~~
t1.interrupt();
//t3.start();
break;
}
}
}
}


IP属地:河南1楼2012-12-11 17:49回复
    目测是..t1.interrupt()后,捕捉到InterruptedException,flag=false,之后不管哪个线程执行都只执行this.notify,故所有线程执行完毕,程序退出


    IP属地:福建2楼2012-12-11 18:04
    回复
      2025-09-12 09:58:35
      广告
      不感兴趣
      开通SVIP免广告
      经过测试我发现,在t1被被唤醒的时候
      example发生变化导致了t2、t3发生了变化
      具体原因解释不了,估计只是sun公司的想法


      IP属地:广东3楼2012-12-11 18:07
      回复
        你说的程序退出,是指的打印出end...吗?
        主线程和t1、t2、t3是独立的线程,你的main方法中并没有刻意要等t1、t2、t3运行结束,所以主线程可以先行结束的(即其他几个线程还在运行,主线程已经结束了)。。。


        IP属地:法国4楼2012-12-11 18:41
        回复