以下是源码: class Resource { private int num = 0; private static boolean flag = true;//等于true说明可以加,等于false说明可以减
public synchronized int add() {
try {
if (!this.flag) {
//如果等于false,说明线程需要等待做减法,
super.wait();
}
Thread.sleep(1000);
num++;
this.flag = false;
super.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
return this.num;
}
public synchronized int sub() {
try {
if (this.flag) {
//如果等于true,说明线程需要等待做加法
super.wait();
}
Thread.sleep(10);
num--;
this.flag = true;
super.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
return this.num;
}
}
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++) {
int add = this.resource.add();
System.out.println(Thread.currentThread().getName() + " 执行加法,num = " + add);
}
}
}
class SubThread implements Runnable { private Resource resource;
public SubThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
int sub = this.resource.sub();
System.out.println(Thread.currentThread().getName() + " 执行减法,num = " + sub);
}
}
}
public static void main(String[] args) throws Exception { Resource resource = new Resource(); AddThread addThread1 = new AddThread(resource); AddThread addThread2 = new AddThread(resource); SubThread subThread1 = new SubThread(resource); SubThread subThread2 = new SubThread(resource); new Thread(addThread1, "加法1").start(); new Thread(addThread2, "加法2").start(); new Thread(subThread1, "减法1").start(); new Thread(subThread2, "减法2").start();
}
我希望能得到返回的加法和减法之后的值是0或者1,但实际得到了
减法2 执行减法,num = -2 加法2 执行加法,num = -1 减法1 执行减法,num = -2 加法1 执行加法,num = -1 减法2 执行减法,num = -2 加法2 执行加法,num = -1 减法1 执行减法,num = -2 加法1 执行加法,num = -1 减法1 执行减法,num = -2 减法2 执行减法,num = -3 加法2 执行加法,num = -2 加法1 执行加法,num = -1 减法1 执行减法,num = -2 减法2 执行减法,num = -3 加法2 执行加法,num = -2 减法1 执行减法,num = -3
求大神指点
wait,notify,notifyAll方法需要放在同步块里面使用,并且判断的竞态需要使用while循环进行判断,不能使用if.
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。