たとえば、 a を使用して、特定のスレッドに対して 1 回だけインスタンス化できるクラスがありThreadLocal
ます。
public class MyClass {
private static final ThreadLocal<MyClass> classInstance =
new ThreadLocal<MyClass>() {
@Override protected MyClass initialValue() {
return new MyClass();
}
};
private MyClass() {
}
public static MyClass getInstance() {
return classInstance.get();
}
}
ここで、これらのスレッド固有のインスタンスに別のスレッドからアクセスできるようにしたいので、そのような解決策になります: https://stackoverflow.com/a/5180323/1768736
この解決策は、スレッド固有の ID (たとえば、 a ) をキーとして使用してMap
(私は a に行きます) を使用することです。キーとして使用することを検討していました (スレッド ID を再利用できるという事実に対処するためのメカニズムを提供します)。ConcurrentHashMap
Map<long, MyClass>
Thread.currentThread().getId()
ただし、このスレッド ID を公開する必要があることを意味します。たとえば、次のようになります。
public class MyClass {
...
public long getId() {
//return the key associated with this MyClass instance in the Map.
//in my case, this would be the ID of the Thread
}
public static MyClass getMyClass(long threadId) {
//allow a Thread to access the MyClass instance of another Thread by providing an ID,
//in my case, that would be the Thread ID
}
}
だから私の質問は: スレッドの ID (によって返されたものThread.getId()
) を公開するのは悪い習慣ですか、それとも心配する必要はありませんか? 理由はわかりませんが、そうすべきではないと腸が教えてくれます。