class MyThread implements Runnable
{
    public int[] b;
    MyThread(int[ ] a)
{
   b =a; 
}
public void run()
 {
  synchronized(b)
    {   
try{
                               b.notify();
                    System.out.println("I am thread "+Thread.currentThread().getName()+"jin ru");
       b.wait();
      System.out.println("I am thread "+Thread.currentThread().getName()+"wake up");
 
}
catch(InterruptedException e)
{

}
    }
     }
}
class test
{
public static void main(String[] b)
{
    int[ ] a ={0};
   MyThread one =new MyThread(a);
   MyThread two =new MyThread(a);
   Thread   one_thread =new Thread(one,"1");
   Thread   two_thread =new Thread(two,"2");
   
       one_thread.start();
       two_thread.start();
      //System.out.println("I am thread "+Thread.currentThread().getName()+"run");
}
}
//  运行结果是 1线程先进入 最后线程2 一直在等待导致主线程都无法结束, wait是释放cpu运行资格同时释放锁我能理解,但是notify在synchronized模块运行完毕后释放锁,如果是在这样1线程synchronized模块运行完毕后就会释放锁,在wait中的2线程就应该能运行而不是一直wait导致主线程一直阻塞,求大神解答?
运行结果:
I am thread 1jin ru
I am thread 2jin ru
I am thread 1wake up

解决方案 »

  1.   

    一般wait() 和notify()都应该在一个条件块里面
      

  2.   

    public void run() {
    synchronized (b) {
    try {
    b.notify();
    System.out.println("I am thread "
    + Thread.currentThread().getName() + " jin ru");
    b.wait();
    System.out.println("I am thread "
    + Thread.currentThread().getName() + " wake up");
    b.notify();
    } catch (InterruptedException e) {
    }
    }
    }
    2号等待时没有东西去唤醒他,代码这样就可以了,结果如下
    I am thread 1 jin ru
    I am thread 2 jin ru
    I am thread 1 wake up
    I am thread 2 wake up