qq_39088116 2020-02-17 21:12 采纳率: 0%
浏览 387

关于四个线程同步控制数字加减的问题

Resource类中的add()方法和sub()方法首先if判断flag状态,如果为true应该执行 this.wait()线程进入等待状态。如果为false执行else{}中的语句。按理说if(){}后的语句不用else{}扩起来应该不影响功能的实现,看视频老师就没用else{}括起来if后的语句,可是我的代码如果不用else{}把if后的语句扩起来就达不到效果。求解答是为什么!!琢磨了好久,能力有限没想明白。

public class AddSubThreadDemo {
    public static void main(String[] args) {
        Resource rsc = new Resource();
        AddThread at = new AddThread(rsc);
        SubThread st = new SubThread(rsc);
        new Thread(at, "加法线程 - A").start();
        new Thread(at, "加法线程 - B").start();
        new Thread(st, "减法线程 - X").start();
        new Thread(st, "减法线程 - Y").start();
    }
}

class Resource {
    private int num = 0;
    private boolean flag = true; // 如果flag为true,执行加法操作;如果flag为false,执行减法操作。

    //加法方法
    public synchronized void add() throws Exception {
        if (this.flag == false) {
            super.wait();
        }else {                          //这里的else{}去掉就会出现错误结果
        Thread.sleep(100);
        this.num++;
        System.out.println("【加法操作 - " + Thread.currentThread().getName() + "】num = " + this.num);
        this.flag = false;
        super.notifyAll();}
    }

    //减法方法
    public synchronized void sub() throws Exception {
        if (this.flag == true) {
            super.wait();
        }else {               //这里的else{}去掉就会出现错误结果
        Thread.sleep(200);
        this.num--;
        System.out.println("【减法操作 - " + Thread.currentThread().getName() + "】num = " + this.num);
        this.flag = true;
        super.notifyAll();}
    }
}

//加法线程
class AddThread implements Runnable {
    private Resource resource;

    public AddThread(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                this.resource.add();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

//减法线程
class SubThread implements Runnable {
    private Resource resource;

    public SubThread(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        for (int j = 0; j < 100; j++) {
            try {
                this.resource.sub();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  • 写回答

3条回答 默认 最新

  • JonathanYan 2020-02-17 22:13
    关注

    这是一个两个程序交替抢夺资源的情形,如题true是加,false是减。
    if的意思是如果不是自己需要的bool值,就等待。
    else的意思是如果是自己的bool值,就运行对应函数,并反转bool让另一程序被唤醒执行。

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题