黑马程序员技术交流社区

标题: hashMap非线程安全,谁能给个简单易懂的例子 [打印本页]

作者: luqh    时间: 2015-3-17 21:58
标题: hashMap非线程安全,谁能给个简单易懂的例子
hashMap非线程安全,谁能给个简单易懂的例子?
作者: rhui    时间: 2015-3-17 22:13
刚看到集合这里,表示不懂
作者: luqh    时间: 2015-3-18 09:49
自己参照网上的例子写了一下,感觉挺明白的
作者: luqh    时间: 2015-3-18 09:51
额。代码没贴进去
  1. public class HashMapThread {
  2. public static final HashMap<String,String> firstHashMap = new HashMap<String, String>();


  3. public static void main(String[] args) throws Exception {
  4. //线程1
  5. Thread t1 = new Thread(){
  6. public void run(){
  7. for(int i=0;i<25;i++){
  8. firstHashMap.put(String.valueOf(i), String.valueOf(i));
  9. }

  10. }
  11. };
  12. Thread t2 = new Thread(){
  13. public void run(){
  14. for(int j=25;j<50;j++){
  15. firstHashMap.put(String.valueOf(j), String.valueOf(j));
  16. }
  17. }
  18. };
  19. t1.start();
  20. t2.start();
  21. Thread.currentThread().sleep(1000);//注线程休息1秒,以便于t1,t2链各个线程填充firstHashMap完成
  22. //如果key和value不同,说明两个线程在同步的时候HashMap出现了异常
  23. for(int l = 0;l<50;l++){
  24. if(!String.valueOf(l).equals(firstHashMap.get(String.valueOf(l)))){
  25. System.out.println(String.valueOf(l)+":"+firstHashMap.get(String.valueOf(l)));
  26. }
  27. }
  28. }
  29. }
  30.             自己验证之后的结果是:
  31.             2:null
  32.             5:null
  33.             7:null
  34.             9:null
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2