不能保证全局唯一,但是可以线程唯一
package com.geely.design.pattern.creational.singleton;
/**
* Created by geely
*/
public class ThreadLocalInstance {
private static final ThreadLocal<ThreadLocalInstance> threadLocalInstanceThreadLocal
= new ThreadLocal<ThreadLocalInstance>(){
@Override
protected ThreadLocalInstance initialValue() {
return new ThreadLocalInstance();
}
};
private ThreadLocalInstance(){
}
public static ThreadLocalInstance getInstance(){
return threadLocalInstanceThreadLocal.get();
}
}
本文介绍了一种使用ThreadLocal实现线程唯一实例的方法,通过覆盖initialValue方法创建ThreadLocalInstance对象,确保每个线程拥有独立的实例。
176万+

被折叠的 条评论
为什么被折叠?



