因为CPU、内存、I/O 设备的速度差别,为了合理利用 CPU 的高性能,平衡这三者的速度差别,计算机体系机构、操做系统、编译程序都作出如下处理:java
public class Test { private long count = 0; private void add10K() { int idx = 0; while(idx++ < 10000) { count += 1; } } public static long calc() { final Test test = new Test(); // 建立两个线程,执行 add() 操做 Thread th1 = new Thread(()->{ test.add10K(); }); Thread th2 = new Thread(()->{ test.add10K(); }); // 启动两个线程 th1.start(); th2.start(); // 等待两个线程执行结束 th1.join(); th2.join(); return count; } }
指令 1:首先,须要把变量 count 从内存加载到 CPU 的寄存器; 指令 2:以后,在寄存器中执行 +1 操做; 指令 3:最后,将结果写入内存(缓存机制致使可能写入的是 CPU 缓存而不是内存)。
public class Singleton { static Singleton instance; static Singleton getInstance(){ if (instance == null) { synchronized(Singleton.class) { if (instance == null) instance = new Singleton(); } } return instance; } }