特点
- 不能保证整个程序唯一;
- 可以保证线程唯一;
ThreadLocal线程单例实现
- 每个线程中拿到的实例都是一个;
- 不同的线程拿到的实例不是一个;
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();
}
}
public class T implements Runnable {
@Override
public void run() {
ThreadLocalInstance instance = ThreadLocalInstance.getInstance();
System.out.println(Thread.currentThread().getName() + " : " + instance);
}
}
public class Test {
public static void main(String[] args) {
ThreadLocalInstance instance = ThreadLocalInstance.getInstance();
System.out.println(Thread.currentThread().getName() + " : " + instance);
instance = ThreadLocalInstance.getInstance();
System.out.println(Thread.currentThread().getName() + " : " + instance);
instance = ThreadLocalInstance.getInstance();
System.out.println(Thread.currentThread().getName() + " : " + instance);
instance = ThreadLocalInstance.getInstance();
System.out.println(Thread.currentThread().getName() + " : " + instance);
instance = ThreadLocalInstance.getInstance();
System.out.println(Thread.currentThread().getName() + " : " + instance);
Thread t1 = new Thread(new T());
Thread t2 = new Thread(new T());
t1.start();
t2.start();
System.out.println("Program End");
}
}
输出:
main : designpattern.creational.singleton.threadlocal.ThreadLocalInstance@52cc8049
main : designpattern.creational.singleton.threadlocal.ThreadLocalInstance@52cc8049
main : designpattern.creational.singleton.threadlocal.ThreadLocalInstance@52cc8049
main : designpattern.creational.singleton.threadlocal.ThreadLocalInstance@52cc8049
main : designpattern.creational.singleton.threadlocal.ThreadLocalInstance@52cc8049
Program End
Thread-0 : designpattern.creational.singleton.threadlocal.ThreadLocalInstance@3d8fd87b
Thread-1 : designpattern.creational.singleton.threadlocal.ThreadLocalInstance@356c6d9c