一个小小程序员 level
获赞
1
粉丝
0
关注
1
看过 TA
12
聊城大学
2023
Java
IP属地:广东
暂未填写个人简介
私信
关注
2024-12-07 21:32
聊城大学 Java
通过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, "a1").start();        new Thread(addThread, "a2").start();        new Thread(subThread, "s1").start();        new Thread(subThread, "s2").start();    }}
0 点赞 评论 收藏
分享

创作者周榜

更多
关注他的用户也关注了:
牛客网
牛客企业服务