JAVA 線程等待喚醒,wait and notify

wait,notify操作是同一個對象鎖,簡單例子如下


package com.cienet.wangbin.test;



public class Test7 {


    /**
     * @param args
     */
    public static void main(String[] args) {
        new Thread1().start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread2().start();
    }


    static class Thread1 extends Thread {
        @Override
        public void run() {
            super.run();
            int count = 10;
            synchronized (Test7.class) {
                for (int i = 0; i < count; i++) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (i == 2) {
                        try {
                            Test7.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(i);
                }
            }
        }
    }


    static class Thread2 extends Thread {
        @Override
        public void run() {
            super.run();
            int count = 10;
            synchronized (Test7.class) {
                for (int i = 0; i < count; i++) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (i == 5) {
                        Test7.class.notify();
                    }
                    System.out.println("b" + i);
                }
            }
        }
    }

}

 如上結果可知,wait是會釋放鎖的,而notify不會釋放鎖,當調用它的時候,不能夠直接喚醒wait住的線程,而是先等其本身執行完畢後才釋放鎖。wait住的資源才能獲取鎖,繼續執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章