單例模式的執行緒安全
阿新 • • 發佈:2018-11-27
package com.day3; public class SingleTonDemo { public static void main(String[] args) { SinleTonThread sinleTonThread=new SinleTonThread(); Thread thread=new Thread(sinleTonThread); thread.start(); Thread thread2=new Thread(sinleTonThread); thread2.start(); } }class SinleTonThread implements Runnable{ @Override public void run() { SingleTon.getinstance(); } } class SingleTon{ private static SingleTon singleTon=null; private SingleTon() { System.out.println("單例模式"); } public static SingleTon getinstance(){if(singleTon==null) { synchronized (SingleTon.class) { if(singleTon==null) { singleTon=new SingleTon(); } } } return singleTon; } }