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
  • 相关阅读:
    排名第一、第二的OCR软件
    补码输出
    枚举 与 枚举的应用
    动态构造结构体数组
    c 冒泡排序
    strcpy
    typedef用法
    C 结构体小结
    int 占一个机器字长
    SQL Server创建视图——视图的作用
  • 原文地址:https://www.cnblogs.com/InformationGod/p/9489320.html
Copyright © 2011-2022 走看看