单例(ThreadLoacal)

普通的

    public static synchronized ThreadScopeShareData getInstance(){
        if (instance==null) {
            instance = new ThreadScopeShareData();
        }
        return instance;
    }
    private static ThreadScopeShareData instance=null;

线程的

    public static ThreadScopeShareData getInstance(){
        ThreadScopeShareData instance= map.get();
        if (instance==null) {
            instance = new ThreadScopeShareData();
            map.set(instance);
        }
        return instance;
    }
    private static ThreadLocal map =new ThreadLocal();

内部类

public class StaticSingleton {
     private StaticSingleton(){
         System.out.println("StaticSingleton is create");
     }
     private static class SingletonHolder {
         private static StaticSingleton instance = new StaticSingleton();
     }
     public static StaticSingleton getInstance() {
         return SingletonHolder.instance;
     }
}

你可能感兴趣的:(单例(ThreadLoacal))