想麻烦各位帮忙解惑啊,下面这段代码在程序中的执行顺序应该是怎样啊?还有对线程中的wait()函数和notifyAll()函数很是迷惑,想请问大家一下,JAVA多线程编程中,wait()函数notifyAll()函数该怎么用呢?如果一个线程调用了wait()函数后,进入停滞状态的是否就是当前线程呢?再次调用notifyAll()函数后,唤起的又是否就是当前线程自身呢?class Thread1 extends Thread{
    private Store st;
    public Thread1(Store st){
       this.st=st;
     }
    public void run(){
       System.out.println(Thread.currentThread().getName()+"启动");
       for(int i=0;i<10;i++){
          try{
             sleep(1000);
            }catch(InterruptedException e){}
          st.storeIn();
        }
     }
}
class Thread2 extends Thread{
    private Store str;
    public Thread2(Store str){
       this.str=str;
     }
    public void run(){
       System.out.println(Thread.currentThread().getName()+"它也启动了");
       for(int i=0;i<10;i++){
          str.storeOut();
        }
     }
}
class Store{
    private static int treasure=0;
    private static boolean available=true;
    public synchronized void storeIn(){
       while(available==false){
          try{
            wait();
           }catch(InterruptedException e){}
       }
       ++treasure;
       System.out.println("storeIn,now treasure:"+treasure);
       available=false;
       notifyAll();
    }
    public synchronized void storeOut(){
       while(available==true){
          try{
             wait();
            }catch(InterruptedException e){}
       }
       --treasure;
       System.out.println("storeOut,now treasure is:"+treasure);
       available=true;
       notifyAll();
    }
}
public class ThreadUse3{
    public static void main(String args[]){
       Store store=new Store();
       Thread1 thread1=new Thread1(store);
       thread1.setName("线程一");
       Thread2 thread2=new Thread2(store);
       thread2.setName("二线程");
       thread1.start();
       thread2.start();
     }
}

解决方案 »

  1.   

    在Java对象中,有两种池
    琐池-----------------------synchronized
    等待池---------------------wait(),notify(),notifyAll()
    如果一个线程调用了某个对象的wait方法,那么该线程进入到该对象的等待池中(并且已经将锁释放),
    如果未来的某一时刻,另外一个线程调用了相同对象的notify方法或者notifyAll方法,
    那么该等待池中的线程就会被唤起,然后进入到对象的锁池里面去获得该对象的锁,
    如果获得锁成功后,那么该线程就会沿着wait方法之后的路径继续执行。
      

  2.   

    wait(),notify(),notifyAll() 都是继承自Objectwait():当前线程等待
    notify():唤醒在此对象监视器上等待的单个线程
    notifyAll():唤醒在此对象监视器上等待的所有线程
      

  3.   

    代码执行的顺序你运行就知道了,意义简单来说就是轮流storeIn和storeOut,并根据treasure变量的值控制storeIn和storeOut的逻辑wait和notifyAll/notify的用法1楼说得很清楚,不过你首先要明确你写的wait和notifyAll相当于this.wait()和this.notifyAll()所以他们释放的是this指向的对象锁
    synchronized意味着只有一个Thread能获得这个对象锁,所以storeIn和storeOut就不可能并发执行,只能是一次一个,当然不确定是哪一个,所以这时候就需要wait和notifyAll来规范
    notifyAll一调用,两个线程就同时开始争夺对象锁,但是如果逻辑应该走storeIn却被执行storeOut的线程得到了对象锁的话,没关系,判断treasure和available变量又再次会让代码回到wait释放对象锁
    两个线程继续争夺,这样通过wait和notifyAll就可以保证多线程按照正确的逻辑进行下去
      

  4.   

    是这样的,不过还有这三个方法只能用在带synchronized 关键字即同步的方法或表达式
      

  5.   

    wait(),notify(),notifyAll() 都是继承自Object wait():当前线程等待 
    notify():唤醒在此对象监视器上等待的单个线程 
    notifyAll():唤醒在此对象监视器上等待的所有线程
    支持这种观点