已退网再见
2020-08-15 21:58
采纳率: 71.4%
浏览 296
已采纳

java多线程中使用for循环和while循环的区别

下面是代码,我的到的结果是number一直是1W,而index一直在1W-2W之间。
请问下这是为什么?

public class MultiThreadsError implements Runnable {
    int index = 0;
    int number = 0;
    int j = 0;
    static MultiThreadsError instance = new MultiThreadsError();

    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);
        System.out.println(instance.number);
    }
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            index++;
        }
        while (number< 10000) {
            number++;
        }
    }
}

5条回答 默认 最新

相关推荐 更多相似问题