JAVA并发编程中Volatile的问题,来高手来大佬?

JAVA并发编程中Volatile的问题,来高手来大佬?

问题描述:

今天研究volatile的时候,发现了一个奇怪的现象,就是按照我这种写法,volatile会不好用,想求大神解释一下到底是为什么?不胜图片说明感激

while(true)才执行while里面的代码,你这个第一个线程一开始就结束了

上面那个老哥是对的
这个是你的版本我稍微改了下

 public class AsTest {
    private static volatile boolean stop = false;

    public static void main(String[] args) throws Exception{
        Thread thread1 = new Thread(()->{
            System.out.println("第一个线程开始");
            while (stop){
                System.out.println("------stop-----");
            }
            System.out.println("第一个线程结束");
        });
        thread1.start();

        Thread.sleep(2000);
        Thread thread2 = new Thread(()->{
            System.out.println("第二个线程开始");
            stop = true;
            System.out.println("第二个线程结束");
        });
        thread2.start();

        //线程1和线程2都结束后才结束程序
        thread1.join();
        thread2.join();

    }
}

运行结果是这样:

第一个线程开始
第一个线程结束
第二个线程开始
第二个线程结束

第一个while循环直接就跳过了,就算你后面改了stop的值,第一个线程早就已经结束了,为时已晚

这个是我猜测你想要的效果改的版本

 public class AsTest {
    private static volatile boolean stop = false;

    public static void main(String[] args) throws Exception{
        Thread thread1 = new Thread(()->{
            System.out.println("第一个线程开始");
            while (true){
                if(stop){
                    System.out.println("------stop-----");
                    break;
                }
            }
            System.out.println("第一个线程结束");
        });
        thread1.start();

        Thread.sleep(2000);
        Thread thread2 = new Thread(()->{
            System.out.println("第二个线程开始");
            stop = true;
            System.out.println("第二个线程结束");
        });
        thread2.start();

        //线程1和线程2都结束后才结束程序
        thread1.join();
        thread2.join();

    }
}

运行结果是这样
第一个线程开始
第二个线程开始
第二个线程结束
------stop-----
第一个线程结束

下面是实际运行的截图
图片说明

图片说明