首页 > 其他 > 详细

并发-可见性-volatile-Unsafe.loadForce

时间:2020-04-09 17:32:20      阅读:115      评论:0      收藏:0      [点我收藏+]
public class VolatileExample {

    public /*volatile*/ boolean isBreak;

    public boolean getBreak() {
        return isBreak;
    }

    public void toBreak() {
        isBreak = true;
        System.out.println("中断标志位isBreak:" + isBreak);

    }

    /**
     * 业务处理线程
     */
    public class LoopThread extends Thread {
        @Override
        public void run() {
            System.out.println("开始处理业务,当isShutdown置为false停止");
            unsafe().loadFence();
            while (!isBreak) {
                unsafe().loadFence();
            }
            ;
            System.out.println("处理业务结束");
        }
    }

    /**
     * 中断线程
     */
    public class BreakThread extends Thread {
        @Override
        public void run() {
            toBreak();

        }
    }

    public static void main(String[] args) {
        try {
            VolatileExample example = new VolatileExample();
            example.new LoopThread().start();
            Thread.sleep(1000);
            example.new BreakThread().start();

            Thread.sleep(1000);
            System.out.println("中断标志位:" + example.getBreak());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static Unsafe unsafe() {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            return (Unsafe) theUnsafe.get(null);
        } catch (Exception e){
            throw new RuntimeException(e);
        }
    }


}

 

并发-可见性-volatile-Unsafe.loadForce

原文:https://www.cnblogs.com/qq610039525/p/12668014.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!