图中为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();
}
}
此后本地执行结果符合预期。
可以提交github,暴露出来问题
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。