我正在处理下面的一段代码。两个线程需要他们自己的单例实例。线程本地是一个明显的解决方案。不过,我仍然面临使用自己的本地副本运行线程的问题。我在几个java类中有一个例子。ThreadLocal与单身人士
public class Singleton1 {
private int i = 0;
private static Singleton1 instance;
private Singleton1() {
}
public static final Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
public int increment() {
return i++;
}
}
public class Holder1 {
private final Singleton1 instance;
public Holder1() {
ThreadLocalSingleton1 singleton1 = new ThreadLocalSingleton1();
instance = singleton1.get();
}
public int increment() {
return instance.increment();
}
private class ThreadLocalSingleton1 extends ThreadLocal<Singleton1> {
@Override
protected Singleton1 initialValue() {
return Singleton1.getInstance();
}
}
}
public class HolderTest {
/**
* @param args
*/
public static void main(String[] args) {
HolderTest test = new HolderTest();
HolderThread thread1 = test.getHolderThread("thread1");
HolderThread thread2 = test.getHolderThread("thread2");
thread1.run();
thread2.run();
}
public HolderThread getHolderThread(String name) {
return new HolderThread(name);
}
private class HolderThread implements Runnable {
String name;
Holder1 holder1 = new Holder1();
public HolderThread(String name) {
this.name = name;
}
@Override
public void run() {
while (true) {
System.out.println(name + " " + holder1.increment());
}
}
}
当ThreadLocal的包装调用的getInstance在辛格尔顿类我不每次都得到一个新的实例?我如何为我的目的做这项工作?
上面的代码是我正在使用的实际代码的简单版本。我有单身人士班,我不能从单身人士改变。我正在创建一个测试客户端,它需要作为单个进程运行,但有很多线程。这些线程中的每一个都需要有它们自己的这些单例实例。
'两个线程需要他们自己的单例实例'根本没有任何意义... – home 2012-02-17 11:26:26
@ user2864740 - 为什么不呢?因为单例的定义是在一个系统中只有一个实例*。系统!=线程。如果你想让人们理解你(和OP)想说的话,你需要常规地使用术语。例如参考维基百科。 – 2015-02-11 22:29:31
如果你知道你只需要对象的两个实例,那么使用[doubleton pattern](https://coderanch.com/t/509003/java/java-doubleton-pattern) – Laxman 2016-12-19 09:29:45