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); }