问题描述
- 为何ThreadLocal返回的值有相同的hashcode?
-
最近在研究多线程,研究到ThreadLocal的时候,修改了一个参考的类,做了测试,发现竟然有的时候ThreadLocal所返回的值有相同的hashcode,百思不得其解,求解答。
下面是代码:
public class TreadLocalTest {
private static ThreadLocalseqNum = new ThreadLocal() {
public A initialValue(){
return new A();
}
};
public A getA(){
// seqNum.set(seqNum.get());
return seqNum.get();
}
public static void main(String[] args){
TreadLocalTest sn = new TreadLocalTest();
TestClient t1 = new TestClient(sn);
TestClient t2 = new TestClient(sn);
TestClient t3 = new TestClient(sn);
TestClient t4 = new TestClient(sn);
t1.start();
t2.start();
t3.start();
t4.start();
}
private static class TestClient extends Thread {
private TreadLocalTest sn;
public TestClient(TreadLocalTest sn){
this.sn = sn;
}
public void run(){
for(int i=0;i<3;i++){
System.out.println("thread["+Thread.currentThread().getName()
+"]sn["+sn.getA().hashCode()+"]");
}
}
}}
这是另一个类,很简单,没有代码
public class A {
}
有时候测试,四个线程都不一样的hashcode,但是有时候,就会出现如下结果:
发现Thread-1,Thread-2所返回的A类竟然有相同的hashcode,为何呢?
thread[Thread-0]sn[28737396]
thread[Thread-0]sn[28737396]
thread[Thread-0]sn[28737396]
thread[Thread-1]sn[6927154]
thread[Thread-1]sn[6927154]
thread[Thread-1]sn[6927154]
thread[Thread-2]sn[6927154]
thread[Thread-3]sn[5442986]
thread[Thread-2]sn[6927154]
thread[Thread-3]sn[5442986]
thread[Thread-2]sn[6927154]
thread[Thread-3]sn[5442986]
解决方案
我运行了你的代码,运行了很多次,出现过一次两个线程返回的A具有相同的hashCode,我也不清楚为什么。
代码结构可以调整一下,ThreadLocal直接放在Thread类中就可以了。
public class TreadLocalTest {
private static class TestClient extends Thread {
private ThreadLocal<A> seqNum = new ThreadLocal<A>() {
public A initialValue() {
return new A();
}
};
public TestClient() {
}
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("thread[" + Thread.currentThread().getName()
+ "]sn[" + seqNum.get().hashCode() + "]");
}
}
}
public static void main(String[] args) {
TestClient t1 = new TestClient();
TestClient t2 = new TestClient();
TestClient t3 = new TestClient();
TestClient t4 = new TestClient();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
时间: 2024-09-12 10:45:50