开发者社区> 问答> 正文

在执行多线程环境下,有使用同步方法,但是为什么还是会多个线程同时执行同个方法

/*


    以下代码想实现的得是对同个变量进行 交替 加减操作。

*
/

public class NumAddSub {
    public static void main(String[] args) {
        Cul cul = new Cul();
        AddThread addThread = new AddThread(cul);
        SubThread subThread = new SubThread(cul);
        new Thread(addThread, "add A").start();
        new Thread(addThread, "add B").start();

        new Thread(subThread, "sub X").start();
        new Thread(subThread, "sub Y").start();


    }
}


class AddThread implements Runnable {

    private Cul cul;

    public AddThread(Cul cul) {
        this.cul = cul;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                this.cul.add();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class SubThread implements Runnable {

    private Cul cul;

    public SubThread(Cul cul) {
        this.cul = cul;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                this.cul.sub();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class Cul {

    private int num = 0;
    private boolean flag = true;  // true为可以执行add,false为执行sub

    public synchronized void add() throws Exception {
        if (!this.flag) {
            super.wait();
        }
        Thread.sleep(10);
        this.num++;
        System.out.println(Thread.currentThread().getName() + " 【add】 num = " + num);
        this.flag = false;
        super.notifyAll();
    }

    public synchronized void sub() throws Exception {
        if (this.flag) {
            super.wait();
        }
        Thread.sleep(20);
        this.num--;
        System.out.println(Thread.currentThread().getName() + " 【sub】 num = " + num);
        this.flag = true;
        super.notifyAll();
    }

}


原本正常执行,但是都后来就发生了问题

image.png

image.png

但都实现了同步方法 image.png

不清楚为何会发生

展开
收起
1322168430376616 2022-02-24 20:00:46 7714 0
9 条回答
写回答
取消 提交回答
  • 6

    2022-03-07 12:30:06
    赞同 展开评论 打赏
  • 11

    2022-03-07 08:41:42
    赞同 展开评论 打赏
  • 6

    2022-03-06 12:40:41
    赞同 展开评论 打赏
  • 6

    2022-03-06 12:34:51
    赞同 展开评论 打赏
  • 人都是这样,安慰别人的时候头头是道,自己遇上了,立马无法自拔,道理都懂,只是情绪作祟,故事太撩人。

    11

    2022-03-06 09:50:18
    赞同 展开评论 打赏
  • 6

    2022-03-04 12:17:56
    赞同 展开评论 打赏
  • 6

    2022-03-04 12:15:26
    赞同 展开评论 打赏
  • 格物致知

    kanyixia

    2022-03-03 09:21:46
    赞同 展开评论 打赏
  • 看看

    2022-02-24 22:35:44
    赞同 展开评论 打赏
滑动查看更多
问答排行榜
最热
最新

相关电子书

更多
多IO线程优化版 立即下载
多线程 立即下载
低代码开发师(初级)实战教程 立即下载

相关实验场景

更多