线程加上system.out.println()不一样的问题

来源:4-3 run方法

Mydog

2020-01-15

package com.mooc.threadpractice;


import java.util.concurrent.TimeUnit;

public class Test1 {
    static boolean isStop = false;

    public static void main(String[] args) throws InterruptedException {
        Thread newThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (!isStop) {
                    i++;
                    System.out.println("i:"+i);
                }
            }
        });
        newThread.start();
        TimeUnit.SECONDS.sleep(1);
        isStop = true;

    }
}

class Test2 implements Runnable {
    static boolean isStop = false;

    public static void main(String[] args) throws InterruptedException {
        Test2 instance = new Test2();
        Thread newThread = new Thread(instance);
        newThread.start();
        TimeUnit.SECONDS.sleep(1);
        isStop = true;
    }


    @Override
    public void run() {
        int i = 0;
        while (!isStop) {
            i++;
        }
    }

}

为什么加上system.out.println一个能终止,一个不能终止?

写回答

1回答

悟空

2020-01-15

system.out.println内部有synchronized,会刷新变量的值,保证可见性。

0
4
悟空
回复
Mydog
后面有一些面试题的哈
2020-01-15
共4条回复

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

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

2512 学习 · 939 问题

查看课程