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让另一程序被唤醒执行。

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型