package com.paddx.test.concurrent; public class Singleton { public static volatile Singleton singleton; /** * 构造函数私有,禁止外部实例化 */ private Singleton() {}; public static Singleton getInstance() { if (singleton == null) { synchronized (singleton) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
package com.paddx.test.concurrent; public class VolatileTest { int a = 1; int b = 2; public void change(){ a = 3; b = a; } public void print(){ System.out.println("b=" b ";a=" a); } public static void main(String[] args) { while (true){ final VolatileTest test = new VolatileTest(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } test.change(); } }).start(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } test.print(); } }).start(); } } }
...... b=2;a=1 b=2;a=1 b=3;a=3 b=3;a=3 b=3;a=1 b=3;a=3 b=2;a=1 b=3;a=3 b=3;a=3 ......
package com.paddx.test.concurrent; public class VolatileTest01 { volatile int i; public void addI(){ i ; } public static void main(String[] args) throws InterruptedException { final VolatileTest01 test01 = new VolatileTest01(); for (int n = 0; n < 1000; n ) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } test01.addI(); } }).start(); } Thread.sleep(10000);//等待10秒,保证上面程序执行完成 System.out.println(test01.i); } }
package com.paddx.test.concurrent; public class MemoryBarrier { int a, b; volatile int v, u; void f() { int i, j; i = a; j = b; i = v; //LoadLoad j = u; //LoadStore a = i; b = j; //StoreStore v = i; //StoreStore u = j; //StoreLoad i = u; //LoadLoad //LoadStore j = b; a = i; } }