老师,关于可见性的问题

来源:9-1 synchronized

张婧仪

2025-01-23

老师,在我没有使用Volatile和Synchronized关键字时,为啥加了睡眠就有可见性,不加就没有可见性呢?
代码如下:

public class ThreadSafeCache {
    int result = 100;

    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSafeCache threadSafeCache = new ThreadSafeCache();
        Visibility visibility = new Visibility(threadSafeCache);
        for (int i = 0; i < 8; i++) {
            Thread thread = new Thread(visibility);
            thread.start();
        }
        Thread.sleep(1000);
        threadSafeCache.setResult(200);
        int x = 1;
        while (true) {
            x++;
        }
    }
}

class Visibility implements Runnable {
    private ThreadSafeCache threadSafeCache;

    public Visibility(ThreadSafeCache threadSafeCache) {
        this.threadSafeCache = threadSafeCache;
    }

    @Override
    public void run() {

        int x = 0;
        while (threadSafeCache.getResult() == 100) {
            x++;
            /**
             * 加了睡眠就有可见性,不加就没有
             */
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
        }
        System.out.println(x);

    }
}
写回答

1回答

翔仔

2025-01-26

同学好,这块看了下 sleep会让出cpu执行权,这块主线程有机会执行后,就能拿到值了

0
2
翔仔
回复
张婧仪
同学好,这个就是背后的原因了呢,sleep了之后,子线程就让出cpu执行权了,之后主线程执行,交换好内存,切换回子线程执行,就拿到值了,再背后就需要看看执行栈了。
2025-01-28
共2条回复

剑指Java面试-Offer直通车 百度资深面试官授课

招聘季即将到来,让百度资深面试官来为你的高薪Offer保驾护航

8444 学习 · 1872 问题

查看课程