Posted on 2010-08-04 17:40
天快黑了 阅读(7891)
评论(23) 编辑 收藏 所属分类:
Question
大家不用关心程序实际逻辑是否正确,只是好奇,为什么这个程序会hang住不运行了?而且CPU会占用100%
import java.util.HashMap;
public class TestLock {
private HashMap map = new HashMap();
public TestLock() {
Thread t1 = new Thread() {
public void run() {
for(int i=0; i<50000; i++) {
map.put(new Integer(i), i);
}
System.out.println("t1 over");
}
};
Thread t2 = new Thread() {
public void run() {
for(int i=0; i<50000; i++) {
map.put(new Integer(i), i);
}
System.out.println("t2 over");
}
};
t1.start();
t2.start();
}
public static void main(String[] args) {
new TestLock();
}
}
Dump thread会看到,程序hang到:
"Thread-1" prio=6 tid=0x00c70bd8 nid=0x914 runnable [0x02ebf000..0x02ebfc68]
at java.util.HashMap.put(HashMap.java:420)
at TestLock$2.run(TestLock.java:20)
"Thread-0" prio=6 tid=0x00c70a50 nid=0x578 runnable [0x02e7f000..0x02e7fb68]
at java.util.HashMap.put(HashMap.java:420)
at TestLock$1.run(TestLock.java:11)