java - wait(),notify(),notifyAll() T2 start! T2 end! T1 start! 为什么会阻塞

查看:81
本文介绍了java - wait(),notify(),notifyAll() T2 start! T2 end! T1 start! 为什么会阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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();
     }
 }

解决方案

rb5 的 object.notify(); 调用时 rb4 还没有进入 wait 状态,因为还在等待锁。线程 start 并不代表马上会自行 run(),也就是说后 start() 的线程的 run() 很有可能先执行。

这篇关于java - wait(),notify(),notifyAll() T2 start! T2 end! T1 start! 为什么会阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆