java - wait(),notify(),notifyAll() T2 start! T2 end! T1 start! 为什么会阻塞
PHP中文网
PHP中文网 2017-04-18 10:53:24
0
2
880
public class Thread04 {
   final Object object = new Object();
Runnable rb4 = new Runnable() {
    public void run(){
        synchronized (object){

                System.out.println("T1 start!");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                object.notify();
                System.out.println("T1 end!");
            }
        }
};
Runnable rb5 = new Runnable() {
    public void run(){
        synchronized (object){
            System.out.println("T2 start!");
            object.notify();
            System.out.println("T2 end!");
            }
        }
};
public static void main(String[] args) {
        Thread04 th = new Thread04();
        new Thread(th.rb4).start();
        new Thread(th.rb5).start();
     }
 }
PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(2)
洪涛

rb5 的 object.notify(); 呼叫時 rb4 還沒有進入 wait 狀態,因為還在等待鎖。執行緒 start 不代表馬上會自行 run(),也就是說後 start() 的執行緒的 run() 很有可能會先執行。

迷茫

rb4在运行获得object的对象锁,输出T1 start!,然后调用wait(),该方法会让rb4挂起,同时释放锁,阻塞。 这时候rb5获得锁,输出T2 start!。然后调用object.notify();,虽然这里打算让rb4运行,但是rb5的锁并没有释放,所以rb4还是处于阻塞。 rb5还是继续运行,输出T2 end!rb5运行结束,释放锁, rb4运行输出T1 end!

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!