Java 多线程加减交替运算为何结果与预期不符?

java 多线程加减交替运算为何结果与预期不符?

java 多线程实现加减交替运算 结果与预期不符

在给出的 java 代码中,作者使用多线程尝试实现加减交替运算,但运行时出现结果与预期不符的问题。代码如下:

class resource {    // 定义一个操作的资源    private int num = 0;        // 定义要进行加减操作的数据    private boolean flag = true;  // flag = true 表示可以进行加法操作,无法进行减法操作                                 // flag = false 表示可以进行减法操作,无法进行加法操作    public synchronized void add() throws interruptedexception {        // 现在需要执行的是减法操作,加法操作需要等待        if (!this.flag) {            super.wait();        }        thread.sleep(100);        this.num++;        system.out.println("[加法操作-" + thread.currentthread().getname() + "]num = " + this.num+ " " + this.flag);        this.flag = false;        super.notifyall();    }    public synchronized void sub() throws interruptedexception {        // 现在进行的是减法操作,加法操作需要等待        if (this.flag) {            super.wait();        }        thread.sleep(200);        this.num--;        system.out.println("[减法操作-" + thread.currentthread().getname() + "]num = " + this.num + " " + this.flag);        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 < 50; i++) {            try {                this.resource.add();            } catch (interruptedexception 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 < 50; i++) {            try {                this.resource.sub();            } catch (interruptedexception e) {                e.printstacktrace();            }        }    }}public class mycalculation {    public static void main(string[] args) {        resource resource = new resource();        addthread addthread = new addthread(resource);        subthread subthread = new subthread(resource);        new thread(addthread, "加法线程a").start();        new thread(addthread, "加法线程b").start();        new thread(subthread, "减法线程a").start();        new thread(subthread, "减法线程b").start();    }}

问题在于,多个线程同时进入 add 或 sub 方法后,可能会出现竞争条件。例如,当 sub 线程进入方法后,如果 flag 为 true,线程将进入 wait() 状态。此时,add 线程可以成功进入方法,将 num 加 1。然后,add 线程将 flag 设置为 false,并唤醒所有等待的线程。但此时,sub 线程仍处于 wait 状态,无法继续执行。当 sub 线程被唤醒后,它将继续执行,并可能将 num 减 1。这样,最终结果可能与预期不符,导致 num 出现负值。

为了解决这个问题,java 中提供了 wait(long) 和 notifyall(long) 方法,可以指定等待时间。通过设置等待时间,可以防止线程处于 wait 状态过久,从而避免出现竞争条件。

算家云 算家云

高效、便捷的人工智能算力服务平台

算家云 37 查看详情 算家云

立即学习“Java免费学习笔记(深入)”;

修改后的代码如下:

public synchronized void add() throws interruptedexception {    // 现在需要执行的是减法操作,加法操作需要等待    while (!this.flag) {        super.wait(10);    }    thread.sleep(100);    this.num++;    system.out.println("[加法操作-" + thread.currentthread().getname() + "]num = " + this.num+ " " + this.flag);    this.flag = false;    super.notifyall(10);}
public synchronized void sub() throws InterruptedException {    // 现在进行的是减法操作,加法操作需要等待    while (this.flag) {        super.wait(10);    }    Thread.sleep(200);    this.num--;    System.out.println("[减法操作-" + Thread.currentThread().getName() + "]num = " + this.num + " " + this.flag);    this.flag = true;    super.notifyAll(10);}

以上就是Java 多线程加减交替运算为何结果与预期不符?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/630506.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月11日 10:56:20
下一篇 2025年11月11日 10:57:06

相关推荐

发表回复

登录后才能评论
关注微信