悟空老师好。在10-3这节中,我出现个问题,代码每次运行结果都是20000

来源:10-3 结果错误

冲哥_

2019-11-15

代码如下:

public class MultiThreadError implements Runnable{
    static MultiThreadError instance = new MultiThreadError();

    int index = 0;

    public static void main(String[] args) throws InterruptedException {

        Thread thread1 = new Thread(instance);
        Thread thread2 = new Thread(instance);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(instance.index);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            index ++;
        }
    }
}

麻烦老师看下是什么问题

写回答

1回答

悟空

2019-11-15

我运行了你的代码,并不是20000,你多运行几次试试看,就用这个代码,我刚才试了:

//img.mukewang.com/szimg/5dce9bc009a1784006600234.jpg

1
1
冲哥_
收到!
2019-11-15
共1条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程