多个线程对hashmap进行put操作的异常
Exception in thread "Thread-0" java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to java.util.HashMap$TreeNode at java.util.HashMap$TreeNode.moveRootToFront(HashMap.java:1832) at java.util.HashMap$TreeNode.treeify(HashMap.java:1949) at java.util.HashMap$TreeNode.split(HashMap.java:2175) at java.util.HashMap.resize(HashMap.java:714) at java.util.HashMap.putVal(HashMap.java:663) at java.util.HashMap.put(HashMap.java:612) at com.stono.thread3.page313.Thread1A.run(Thread1A.java:17)
源码:
package com.stono.thread3.page313; import java.util.HashMap; public class MyService1 { public HashMap<String, String> map = new HashMap<>(); } package com.stono.thread3.page313; import com.stono.thread3.CusPrint; public class Thread1A extends Thread { private MyService1 service1; public Thread1A(MyService1 service1) { super(); this.service1 = service1; } @Override public void run() { for(int i=0;i<50000;i++) { service1.map.put("ThreadA"+(i+1), "ThreadA"+(i+1)); CusPrint.print("ThreadA"+(i+1)); } } } package com.stono.thread3.page313; import com.stono.thread3.CusPrint; public class Thread1B extends Thread { private MyService1 service1; public Thread1B(MyService1 service1) { super(); this.service1 = service1; } @Override public void run() { for(int i=0;i<50000;i++) { service1.map.put("ThreadB"+(i+1), "ThreadB"+(i+1)); CusPrint.print("ThreadB"+(i+1)); } } } package com.stono.thread3.page313; public class Test1_2 { public static void main(String[] args) { MyService1 service1 = new MyService1(); Thread1A a = new Thread1A(service1); Thread1B b = new Thread1B(service1); a.start(); b.start(); } }