线程间变量可见性问题

为什么以下第一种方式的变量,线程间可以直接获取到最新的值,而第二种方式获取不到

package com.silence;

public class TestClass {
    public static void main(String[] args) throws InterruptedException {
        Treadtest treadtest = new Treadtest();
        new Thread(()->{
            treadtest.a=true;
         }).start();
         Thread.sleep(1000);
        System.out.println(treadtest.a);

    }
}
class Treadtest{
    public   boolean a = false;
}

package com.silence;

import java.util.concurrent.TimeUnit;

public class VolatileTest {
public Data myData = new Data();
         class Data{
                   int number =0;
            //int number =0;
            public void add()
            {
                this.number = number +1;
            }
        }
        // 启动两个线程,一个work线程,一个main线程,work线程修改number值后,查看main线程的number
        private static void testVolatile() throws InterruptedException {
            VolatileTest volatileTest = new VolatileTest();

            new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"\t come in");
            try {
                Thread.sleep(2000);
                volatileTest.myData.add();
                System.out.println(Thread.currentThread().getName()+"\t update number value :"+volatileTest.myData.number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "workThread").start();
            Thread.sleep(10);
        //第2个线程,main线程
        while (volatileTest.myData.number == 0){
            //main线程还在找0
        }

        System.out.println(Thread.currentThread().getName()+"\t mission is over");
        System.out.println(Thread.currentThread().getName()+"\t mission is over,main get number is:"+volatileTest.myData.number);
    }
        public static void main(String[] args) throws InterruptedException {
        testVolatile();
    }

}
讨论数量: 1

有没有一种可能,就是前面线程还没执行完,或者执行结束,但是没把数据写回内存;第二段这么改就可以

 Thread workThread = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t come in");
            try {
                Thread.sleep(2000);
                volatileTest.myData.add();
                System.out.println(Thread.currentThread().getName() + "\t update number value :" + volatileTest.myData.number);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "workThread");
        workThread.start();
        workThread.join(); //只加了这一行
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!