volvo_5555 2015-11-18 06:10 采纳率: 0%
浏览 1857

为何ThreadLocal返回的值有相同的hashcode?

最近在研究多线程,研究到ThreadLocal的时候,修改了一个参考的类,做了测试,发现竟然有的时候ThreadLocal所返回的值有相同的hashcode,百思不得其解,求解答。
下面是代码:
public class TreadLocalTest {
private static ThreadLocal seqNum = 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]

  • 写回答

1条回答 默认 最新

  • wanghang1208 2015-11-18 10:02
    关注

    我运行了你的代码,运行了很多次,出现过一次两个线程返回的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();
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用