Java中notify()不能唤醒的问题

查看:190
本文介绍了Java中notify()不能唤醒的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

当AAAA执行到i=50时使用wait(),并使用notify()方法唤醒BBBB,但是一直唤醒失败,请问怎么解决

public class MyThreadTest01 {
    public static void main(String[] args) {
        Mythread mythread = new Mythread();
        Thread01 thread01 = mythread.new Thread01();
        thread01.setName("AAAA");
        mythread.setT1(thread01);
    
        Thread02 thread02 = mythread.new Thread02();
        thread02.setName("BBBB");
        thread01.start();
        thread02.start();
    }
}

public class Mythread {

    private Object obj = new Object();
    private Thread01 t1;
    public Thread01 getT1() {
        return t1;
    }
    public void setT1(Thread01 t1) {
        this.t1 = t1;
    }

    class Thread01 extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println(this.getName() + " " + i);
                            synchronized (obj) {
                    if (i == 50) {
                        try {        
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    class Thread02 extends Thread {
        @Override
        public void run() {            
                synchronized (obj) {
                    obj.notify();
            }
        }
    }
}

解决方案

这是因为出现了这样一个情况,cpu先执行了Thread02的obj.notify方法(当前没有任何线程阻塞),再执行到Thread01的obj.wait方法,这时Thread01在等待其他线程来唤醒自己,遗憾的是Thread02已经执行完了,因此Thread01会永远阻塞。
你改成这样就可以了:

public class MyThreadTest01 {
    public static void main(String[] args) throws Exception {
        Mythread mythread = new Mythread();
        Thread01 thread01 = mythread.new Thread01();
        thread01.setName("AAAA");
        mythread.setT1(thread01);
    
        Thread02 thread02 = mythread.new Thread02();
        thread02.setName("BBBB");
        thread01.start();
        Thread.sleep(3000);
        thread02.start();
    }
}

这篇关于Java中notify()不能唤醒的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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