这是关于Java多线程可见性的问题

时间:2019-04-26 15:13:53

标签: java multithreading volatile

我知道volatile保证可见性,但是我无法理解以下代码。 我还想知道何时将线程变量写入主存储器? 为什么我不能++中断线程system.out.println

package demo.demo2;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class VolatileTest extends Thread {

    static boolean flag = false;
    //    static volatile boolean flag = false;
    int i = 0;

    public VolatileTest() {

    }

    public void run() {
        while (!flag) {
            i++;


            /**
             * When I uncomment the next line of code the child thread stops, and when I comment the child thread does not stop
             */
//            System.out.println("22");
//
        }
    }

    public static void main(String[] args) throws Exception {
//        -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly
        VolatileTest vt = new VolatileTest();
        vt.start();
        Thread.sleep(2000);
        vt.flag = true;
//        System.out.println(vt.flag);

        System.out.println("stope" + vt.i);
    }


}

0 个答案:

没有答案