多线程练习之数字加减

数字加减

题目:设计 4 个线程对象,两个线程执行减操作,两个线程执行加操作,使其返回结果为0 1 0 1…或为0 -1 0 -1…:

public class ThreadTest {
    public static void main(String[] args) {
        System.out.println("开始了");
        Number number = new Number();
        AddThread addThread = new AddThread(number);
        SubThread subThread = new SubThread(number);
        new Thread(addThread, "加线程1").start();
        new Thread(addThread, "加线程2").start();
        new Thread(subThread, "减线程1").start();
        new Thread(subThread, "减线程2").start();
    }
}

class AddThread implements Runnable {
    private Number num;

    public AddThread(Number num) {
        this.num = num;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                this.num.setAdd();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class SubThread implements Runnable {
    private Number num;

    public SubThread(Number num) {
        this.num = num;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                this.num.setSubtract();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

class Number {
    private int num = 0;
    private boolean flag = true;// true 可以加 false可以减

    public synchronized void setAdd() throws InterruptedException {
        while (!this.flag) // 这里不能使用if判断
            this.wait();
        Thread.sleep(100);
        this.num++;
        System.out.println(Thread.currentThread().getName() + "加操作,----num: " + num);
        this.flag = false;
        this.notifyAll();
    }

    public synchronized void setSubtract() throws InterruptedException {
        while (this.flag) // 这里不能使用if判断
            this.wait();
        Thread.sleep(200);
        this.num--;
        System.out.println(Thread.currentThread().getName() + "减操作,减:----num: " + num);
        this.flag = true;
        this.notifyAll();
    }
}

这里有一个坑,在阿里培训中有一个问题,如果在Number类中增加或者减数时使用if判断,这样如果是2个线程以上的话就会出现synchronized锁不生效的问题

因为当一个线程在进行减操作时,有两个线程依次进入加方法中,当第一个wait()第二个线程就可以进入,继续wait(),当减操作结束后,notifyAll所有线程,就会出现两个加操作的线程继续往下走,导致加二,减一的情况。

使用while函数会重新判断是否满足条件,不满足继续阻塞,就可以解决此问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值