java Object类的wait和notify学习

public class ThreadTest2 {

    public static void main(String[] args) {

        Sample sample = new Sample();

        IncreaseThread thread1 = new IncreaseThread(sample);

        DecreaseThread thread2 = new DecreaseThread(sample);

        thread1.start();
        thread2.start();



    }

}

class Sample {

    private int number;

    // 增加
    public synchronized void increase() {

        if (number != 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number++;
        notify();

        System.out.println(" increase = " + number);
    }

    // 减少
    public synchronized void decrease() {
        if (number == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        number--;
        notify();

        System.out.println(" decrease = " + number);
    }

}

class IncreaseThread extends Thread {

    private Sample sample;

    public IncreaseThread(Sample sample) {
        this.sample = sample;
    }

    public void run() {
        super.run();
        while (true)
            sample.increase();
    }
}

class DecreaseThread extends Thread {

    private Sample sample;

    public DecreaseThread(Sample sample) {
        this.sample = sample;
    }

    public void run() {
        super.run();
        while (true)
            sample.decrease();
    }
}


两个线程的情况下这段代码能实现number 加-减-的的效果,number 的实现始终是0和一

如果开四个线程,两个加、两个减,以上代码就无法实现

        Sample sample = new Sample();

        IncreaseThread thread1 = new IncreaseThread(sample);
        IncreaseThread thread2 = new IncreaseThread(sample);

        DecreaseThread thread3 = new DecreaseThread(sample);    
        DecreaseThread thread4 = new DecreaseThread(sample);

        thread1.start();
        thread2.start();

        thread3.start();
        thread4.start();


原因分析:12线程负责增加,34负责减小,假如3线程先进入decrease方法,这个时候nubmer==0,条件为true3线程等待(wait),由于wait具有释放锁的功能,其他线程这个时候都可以访问该对象synchronized 方法,假如4线程也进入decrease方法,number还是为零,这个时候34线程都处于等待状态。假如1线程进入increase,判断number的值,number为零,条件为假,执行number++,number值变成一并且打印值,再执行notify,由于34线程都处于等待状态,不知道会notify哪个线程,假如唤醒3号线程,执行number--,number值变成零,再notify,由于4线程还是wait状态,假如4线程被唤醒,执行number--,这个时候number就变成了-1,由于这一步错了后面肯定接着错。


具体解决办法,期待各位网友给出答案,我把if改成while,也没用





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值