三段有意思的代码让你思考volatile和cpu缓存

代码一

package main.java.mo.multithread.volatiletest;

public class CacheVolatile {
    private  int i = 0;

    public void write() {
        i++;
    }

    public int read() {
        while (i == 0) {

        }
        return i;
    }

    public static void main(String[] args) {
        CacheVolatile cacheVolatile = new CacheVolatile();

        Thread thread = new Thread(() -> {
            cacheVolatile.read();
        });
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10000; i++)
            cacheVolatile.write();

    }
}

代码二

package main.java.mo.multithread.volatiletest;

public class CacheVolatile {
    private  int i = 0;

    public void write() {
        i++;
    }

    public int read() {
        while (i == 0) {
            System.out.println(i);
        }
        return i;
    }

    public static void main(String[] args) {
        CacheVolatile cacheVolatile = new CacheVolatile();

        Thread thread = new Thread(() -> {
            cacheVolatile.read();
        });
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10000; i++)
            cacheVolatile.write();

    }
}

代码三

package main.java.mo.multithread.volatiletest;

public class CacheVolatile {
    private volatile int i = 0;

    public void write() {
        i++;
    }

    public int read() {
        while (i == 0) {
            
        }
        return i;
    }

    public static void main(String[] args) {
        CacheVolatile cacheVolatile = new CacheVolatile();

        Thread thread = new Thread(() -> {
            cacheVolatile.read();
        });
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10000; i++)
            cacheVolatile.write();

    }
}

分析

这三段代码执行结果自然各有差异,分析这三段代码可以让你理解volatile和缓存的知识点。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 181,004评论 25赞 708
  • volatile 关键字解析 原文出处: 海子volatile 这个关键字可能很多朋友都听说过,或许也都用过。在 ...
    常青大侠阅读 705评论 0赞 4
  • 申明:本篇文章将复习一些数学概念,来自于百度百科 概述 导数(Derivative)是微积分中的重要基础概念。当函...
    Alfie20阅读 3,386评论 0赞 5
  • 从云南发的茶叶,已经尽十天了,还没有到,致使工作不能开展起来。也是醉了。好像只能耐心等待别无它法。很多次,我...
    梅燕霓阅读 177评论 0赞 1

友情链接更多精彩内容