开发者社区> 问答> 正文

java高级编程中的第6章学习视频中的数字加减代码问题

image.png

图中为Resouce类中的同步加减法操作, 但是该操作我在本地运行的时候出现了错误,并不是预期的1,0,1,0……; 我分析是两个减法操作线程同时在进入flag条件后均进入等待,加法执行完以后同时notifyAll操作同时唤醒两个线程导致执行了下面的代码; 于是我本地进行了改进,代码如下:

public synchronized void add() throws Exception {
    if (!flag) {
        super.wait();
        add();
    } else {
        Thread.sleep(100);
        this.num++;
        System.out.println("加法操作++" + Thread.currentThread().getName() + "num = " + this.num);
        flag = false;
        super.notifyAll();
    }
}

public synchronized void sub() throws Exception {
    if (flag) {
        super.wait();
        sub();
    } else {
        Thread.sleep(100);
        this.num--;
        System.out.println("减法操作--" + Thread.currentThread().getName() + "num = " + this.num);
        flag = true;
        super.notifyAll();
    }

}

此后本地执行结果符合预期。

展开
收起
冷月寒风 2020-03-31 19:09:48 727 0
1 条回答
写回答
取消 提交回答
  • 技术架构师 阿里云开发者社区技术专家博主 CSDN签约专栏技术博主 掘金签约技术博主 云安全联盟专家 众多开源代码库Commiter

    可以提交github,暴露出来问题

    2020-04-01 18:09:15
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载