zoukankan      html  css  js  c++  java
  • synchronized无法禁止指令重排序的证明

    package demo.reorder;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class SynchronizedDemo {
        private static volatile int i = 0;
        private static volatile int j = 0;
            
        public static void main(String[] args) {
            Runnable thread1  = new Runnable() {
                
                @Override
                public void run() {
                    while(true)
                    selfPlus();
                }
            };
            
            Runnable thread2 = new Runnable() {
                
                @Override
                public void run() {
                    while(true)
                    print();
                }
            };
            
            ExecutorService pool = Executors.newFixedThreadPool(2);
            pool.execute(thread1);
            pool.execute(thread2);
            pool.shutdown();
        }
        
        public static synchronized void selfPlus() {
    //        if(i != j)
    //        System.out.println("selfPlus: i= "+i+" ; j= "+j);
            i++;
            j++;
    //        if(i != j)
    //        System.out.println("selfPlus: i= "+i+" ; j= "+j);
        }
        
        public static void print(){
            if(i < j)
            System.out.println("i= "+i+" ; j= "+j);
        }
    
    }
    View Code
  • 相关阅读:
    26.列表的循环遍历
    效率比较--链表
    心之距离 再回首 光年之遥远
    效率比较--集合
    效率比较--数组
    哈希表
    栈 VS 队列
    struts1 标签引入
    web 连接池配置
    zip&ftp命令
  • 原文地址:https://www.cnblogs.com/InformationGod/p/9489320.html
Copyright © 2011-2022 走看看