wait

package com.gupaoedu.vip.spring.exam.thread;

/**
 * @author Jly
 * @date 2019/7/30  14:00
 */
public class Service {

    public void mSleep(){
        synchronized(this){
            try{
                Thread.sleep(3*1000);
                System.out.println(" notifyAll喚醒等待前 。 結束時間:"+System.currentTimeMillis());
                this.notifyAll();
                System.out.println(" notifyAll喚醒等待後 。 結束時間:"+System.currentTimeMillis());
            }
            catch(Exception e){
                System.out.println(e);
            }

        }

    }

    public void mWait(){

        synchronized(this){
            try{
                System.out.println(" wait等待開始 。 當前時間:"+System.currentTimeMillis());
                this.wait();
                System.out.println(" wait等待結束 。 當前時間:"+System.currentTimeMillis());
            }catch(Exception e){
                System.out.println(e);
            }
        }

    }

    public static void main(String[] args) {
        Service mService = new Service();

        Thread sleepThread = new Thread(new SleepThread(mService));
        Thread waitThread = new Thread(new WaitThread(mService));
        sleepThread.start();
        waitThread.start();
        //執行結果:
//        wait等待開始 。 當前時間:1564467228874
//        notifyAll喚醒等待前 。 結束時間:1564467231875
//        notifyAll喚醒等待後 。 結束時間:1564467231875
//        wait等待結束 。 當前時間:1564467231875

    }

}
  • 執行結果說明什麼,wait沒有釋放鎖,直到notifyAll 喚醒,才執行完下面的代碼釋放鎖
相關文章
相關標籤/搜索