package J20250802;

/**
 * @author WanJl
 * @version 1.0
 * @title asd
 * @description
 * @create 2025/8/2
 */
public class asd {
    private boolean flag = false;

    public static void main(String[] args) throws InterruptedException {
        asd example = new asd();

        Thread t1 = new Thread(() -> {
            while (!example.flag) {
                // 空循环
            }
            System.out.println("循环结束");
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            example.flag = true;
            System.out.println("设置flag为true");
        });

        t1.start();
        t2.start();
    }
}
class ReliableVolatileDemo {
    private static /*volatile*/ boolean flag = false; // 测试时注释/取消注释volatile

    public static void main(String[] args) throws InterruptedException {
        // Writer线程：修改flag
        new Thread(() -> {
            System.out.println("Writer启动, 2秒后设置flag=true");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = true;
            System.out.println("Writer: flag已设置为true");
        }).start();

        // Reader线程：检测flag
        new Thread(() -> {
            while (!flag) {
                // 关键点1: 添加JIT无法优化的操作
                Thread.yield(); // 主动让出CPU，增加上下文切换

                // 关键点2: 添加伪耗时操作（JIT不会缓存此类操作）
                double dummy = Math.sin(Math.random());
            }
            System.out.println("Reader: 检测到flag变化");
        }).start();

        Thread.sleep(5000); // 主线程等待
        System.out.println("程序结束, flag状态: " + flag);
    }
}
