/** * @描述 * @参数 $ * @返回值 $ * @创建人 yufeng.lin@ucarinc.com * @创建时间 $ * @修改人和其它信息 */ public class FadeShare implements Runnable{ //数组长度 public static int arrayLength = 4; ///数组 public static VolatileLong []longs = new VolatileLong[arrayLength]; //计算次数 public final static long count_time = 500L * 1000L * 1000L; //操作的角标 ---------------------!!!不能声明成静态因为那样代表一个对象,否则线程在用的时候每次都要去主存中加载多余数据在缓存,获取改值进行计算,占用巨大时间 public final int opIndex; //对数组的元素进行赋值: static{ for (int i = 0; i < longs.length; i++) { longs[i] = new FadeShare.VolatileLong(); } } public FadeShare(int i){ this.opIndex = i; } /** * 设计4个线程,执行同一个计算量 计算前后时间 * @param args * @throws InterruptedException */ public static void main(String args []) throws InterruptedException { //java 准备清空缓存 Thread.sleep(10000); final long start = System.nanoTime(); Thread [] threads = new Thread[arrayLength]; for(int i = 0 ;i< arrayLength; i++){ threads[i] = new Thread(new FadeShare(i)); } for (Thread thread : threads){ thread.start(); } for (Thread thread : threads){ thread.join(); } System.out.println( System.nanoTime() - start ); } @Override public void run() { Long i = count_time; while ( 0 != --i ){ longs[opIndex].value = i; } } //48Bit 注释掉后数组剩下 8个字节 以及对象头12 字节 会 加载 3个 到一个缓存行,其它线程执行时候会造成伪共享,只能到内存读取数据 public final static class VolatileLong{ public volatile long value = 0l; // public long p1,p2,p3,p4; // public int p5; } }