java吧 关注:1,300,753贴子:12,845,414
  • 5回复贴,共1

急!!!!!一个JAVA线程的问题??在线等???

只看楼主收藏回复

public class MyThread extends Thread
{
         static int TOTAL=5;
         final static int PRICE=5;
         int number;
         int money;
         public MyThread(int number,int money)
         {
                this.number=number;
                this.money=money;
         }
         public static void main(String args[])
         {
                  new MyThread(2,20).start();
                  new MyThread(1,20).start();
                  new MyThread(2,10).start();
                  new MyThread(1,10).start();
                  new MyThread(1,5).start();
         }
         public synchronized void run()
         {
                  int back=money-PRICE*number;
                  if(back>TOTAL)
                     
                      try{
                               wait(); 
                         }
                      catch(InterruptedException e)
                         {
                                 throw new RuntimeException(" cannot wait()");
                         }
                  System.out.println("Hello! "+Thread.currentThread().getName()+", this is your "+number+" ticket!we give you back"+back+"yuan");
                  TOTAL=TOTAL+PRICE*number;
                  notifyAll();
         }
}
==========================
请问Thread0和Thread1为什么没有执行呢?也就是前面两个线程没反应,只执行了后面三个线程,而且程序进入了停滞不前的状态??
请问错误在哪里呢?????


1楼2008-05-22 22:08回复
    因为前两个线程传进来的参数满足了你的if条件,所以线程执行了
    wait()...无限等待中...


    2楼2008-05-22 23:45
    回复
      2026-04-02 09:32:54
      广告
      不感兴趣
      开通SVIP免广告
      那后面不是有了一个notifyAll了吗?
      他怎么不会被唤醒呢??


      3楼2008-05-23 12:11
      回复
        • 124.238.69.*
        synchronized是获得当前实例的锁,也就是this。在synchronizedz中调用wait(),将当前线程置入前面说的实例的等待区,等待唤醒,也就是等待调用notifyAll()。wait()和notifyAll()和notify都是object的方法,唤醒被wait()的线程必须是由调用wait()的实例调用notifyAll()。好比
         public class Test extends Thread
         {
         public synchronized void run()
         {
         this.wait();
         } 
         public void myNotify()
         {
         this.notifyAll()
         }
         }
         Test a = new Test();
         a.start();//该线程wait()
         a.myNotify();//只用调用该方法才能唤醒,如果不调用该线程会永远wait下去
         new Test().myNotify()//这并不会唤醒a。因为new Test()和a是两个不同的实例。


        4楼2008-05-23 16:30
        回复
          • 124.238.69.*
          补一句,调用this.wait()方法当前线程必须获得this的锁(java api文档日文版,将这里的锁翻译成监视器,英文不知道).也就是必须在synchronized中调用wait()


          5楼2008-05-23 16:36
          回复
            • 124.238.69.*
            public void myNotify() 
             { 
             this.notifyAll() 
             }这个我忘加synchronized了。抱


            6楼2008-05-23 17:08
            回复