求助:生产者消费者问题

通过wait()和notifyAll()控制2个加法线程和2个减法线程对初始为0的数字分别进行1000次加法和1000次减法。每次加完后通过修改flag标识,使后续只能进行减法操作;每次减完过后,通过修改flag标识,使后续只能进行加法操作。因为数字初始是0,按理说后续加完或减完的数字只能是-1,0或1。结果执行过程中出现了数字2。求助各位大佬帮忙看下是什么问题:
class Resource {
    private int num = 0;
    //操作标识:true/只能进行加法;false/只能进行减法
    private boolean flag = true;

    //加法操作
    public synchronized void add() throws InterruptedException {
        if (this.flag == false) {
            super.wait();
        }
        this.num++;
        System.out.println(Thread.currentThread().getName() + ":加法," + this.num);
        this.flag = false;
        super.notifyAll();
    }

    //减法操作
    public synchronized void sub() throws InterruptedException {
        if (this.flag == true) {
            super.wait();
        }
        this.num--;
        System.out.println(Thread.currentThread().getName() + ":加法," + 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 < 1000; i++) {
            try {
                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 i = 0; i < 1000; i++) {
            try {
                resource.sub();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

public class ThreadDemo10 {

    public static void main(String[] args) {
        Resource res = new Resource();
        AddThread addThread = new AddThread(res);
        SubThread subThread = new SubThread(res);
        new Thread(addThread, &quot;a1&quot;).start();
        new Thread(addThread, &quot;a2&quot;).start();

        new Thread(subThread, &quot;s1&quot;).start();
        new Thread(subThread, &quot;s2&quot;).start();
    }
}
全部评论
补充:当加法线程和减法线程各自只有1个时,不会出现此问题
点赞 回复 分享
发布于 2024-12-07 21:42 广东

相关推荐

不愿透露姓名的神秘牛友
07-01 10:56
点赞 评论 收藏
分享
05-22 09:23
门头沟学院 Java
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
昨天 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务