开发者社区> 问答> 正文

多线程代码同步问题,求解答

已解决

以下是源码: 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

求大神指点

展开
收起
游客ioa25f3wq3p54 2021-03-05 12:52:39 594 0
1 条回答
写回答
取消 提交回答
  • 采纳回答

    wait,notify,notifyAll方法需要放在同步块里面使用,并且判断的竞态需要使用while循环进行判断,不能使用if.

    2021-03-30 22:12:04
    赞同 1 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
多线程 立即下载
fibjs 模块重构从回调到协程 立即下载
fibjs 模块重构从回调到协程--陈垒 立即下载

相关实验场景

更多