拽着尾巴的鱼儿 2022-07-18 21:32 采纳率: 0%
浏览 21

java并发编程临界资源访问

思考,在不运行代码的得情况下,num 最终输出多少?


public class MyThread {
    static volatile Integer num = new Integer(0);


    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> incry(num)).start();
        }
        try {
            Thread.sleep(2000);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("num = " + num);
    }

    private static Integer incry(Integer num) {
        try {
            Thread.sleep(1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        synchronized (MyThread.class) {
            num ++;
        }

        return num;
    }
}

  • 写回答

1条回答 默认 最新

  • GDKbb 2022-07-19 15:26
    关注

    0
    synchronized (MyThread.class)会等待主线程执行完再执行 num++;但是等主线程执行完此时输出的是0

    评论

报告相同问题?

问题事件

  • 创建了问题 7月18日