public class SingleTest { private static SingleTest singleTest; // 这个应该用volatile修饰 //获取单例的方法 public static SingleTest getInstance() { if(singleTest == null){ synchronized (SingleTest.class){ if(singleTest == null){ singleTest = new SingleTest(); } } } return singleTest; } }
//可见性验证 @Test public void testA() throws InterruptedException { //启动线程在不停监视str变化 Thread th1 = new Thread(() -> { while(true){ if(str.equals("b")){ System.out.println("th1 ==> str 已经被改成 b ," + Thread.currentThread()); } } }); Thread th2 = new Thread(() -> { while(true){ synchronized (str){ if(str.equals("b")){ System.out.println("th2 ==> str 已经被改成 b ," + Thread.currentThread()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }); th1.start(); th2.start(); //让监视线程都启动完毕 Thread.sleep(3000); System.out.println("修改str的值为b"); synchronized (str){ str = "b"; } Thread.sleep(3000); }