volatile 线程可见性 证明

没设么好说的 要的就是证明

public class VolatileTest {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();

        Thread thread = new Thread(myRunnable);
        thread.start();

        while (true) {
            if (myRunnable.flag) {
                System.out.println("暂停了");
                break;
            }
        }
    }
}

class MyRunnable implements Runnable {

    public volatile boolean flag = false;

    @Override
    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("修改了值");
        flag = true;
    }
}

posted @ 2020-08-04 22:18  z_先生  阅读(180)  评论(0编辑  收藏  举报