线程的可见性问题
  • 板块学术版
  • 楼主Leonora_
  • 当前回复1
  • 已保存回复1
  • 发布时间2024/7/17 00:02
  • 上次更新2024/7/17 09:06:07
查看原帖
线程的可见性问题
1375895
Leonora_楼主2024/7/17 00:02

为什么我在while循环中让main线程休眠100毫秒,也可以解决flag的可见性问题

public class VolatileThreadTest {
    public static void main(String[] args) throws InterruptedException {
        // 创建VolatileThread线程对象
        VolatileThread volatileThread = new VolatileThread();
        volatileThread.start();

        // main方法
        while (true) {
            if (volatileThread.isFlag()) {
                System.out.println("执行了======");
            }
            //让线程休眠100毫秒
            Thread.sleep(100);
        }
    }
}

class VolatileThread extends Thread {
    // 定义成员变量
    private boolean flag = false;

    public boolean isFlag() {
        return flag;
    }

    @Override
    public void run() {
        // 线程休眠1秒
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 将flag的值更改为true
        this.flag = true;
        System.out.println("flag=" + flag);
    }
}
2024/7/17 00:02
加载中...