51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 1594|回复: 0
打印 上一主题 下一主题

ArrayList的线程安全测试

[复制链接]
  • TA的每日心情
    郁闷
    2022-8-29 14:43
  • 签到天数: 1 天

    连续签到: 1 天

    [LV.1]测试小兵

    跳转到指定楼层
    1#
    发表于 2018-4-27 17:07:57 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    1. public class TestThread implements Runnable{  
    2.   
    3.     private List list;  
    4.     CountDownLatch cdl;  
    5.       
    6.       
    7.     public TestThread(List list,CountDownLatch cdl){  
    8.         this.list=list;  
    9.         this.cdl=cdl;  
    10.     }  
    11.     /**
    12.      * @see java.lang.Runnable#run()
    13.      */  
    14.     @Override  
    15.     public void run() {  
    16.         for(int i=0;i<500;i++){  
    17.             list.add("a");  
    18.         }     
    19.         try {  
    20.             cdl.countDown();  
    21.         } catch (Exception e) {  
    22.             e.printStackTrace();  
    23.         }  
    24.     }  
    25.       
    26.     public static void main(String[] args) throws Exception{  
    27.         int count=32;  
    28.         CountDownLatch cdl=new CountDownLatch(count);  
    29.         List list=new ArrayList();  
    30.         //List list=Collections.synchronizedList(new ArrayList());  
    31.         TestThread t1=new TestThread(list,cdl);  
    32.         for(int i=0;i<count;i++){  
    33.             new Thread(t1).start();  
    34.         }         
    35.         cdl.await();  
    36.         System.out.println("size:"+list.size());  
    37.     }  
    38.   
    39. }
    复制代码

    复制代码
    结论是,用ArrayList时,出现如下错误:

    Exception in thread "Thread-1" java.lang.ArrayIndexOutOfBoundsException: 452  
        at java.util.ArrayList.add(ArrayList.java:352)  
    改为List list=Collections.synchronizedList(new ArrayList())之后,就正常了。



    List<Map<String,Object>> data=new ArrayList<Map<String,Object>>();

            那么为了解决这个线程安全问题你可以这么使用Collections.synchronizedList(),如:

            List<Map<String,Object>> data=Collections.synchronizedList(new ArrayList<Map<String,Object>>());

           其他的都没变,使用的方法也几乎与ArrayList一样,大家可以参考下api文档;

    额外说下 ArrayList与LinkedList;这两个都是接口List下的一个实现,用法都一样,但用的场所的有点不同,Array
    List适合于进行大量的随机访问的情况下使用,LinkedList适合在表中进行插入、删除时使用,二者都是非线程安
    全,解决方法同上(为了避免线程安全,以上采取的方法,特别是第二种,其实是非常损耗性能的)。



    线程安全和非线程安全  

    ArrayList和Vector有什么区别?HashMap和HashTable有什么区别?StringBuilder和StringBuffer有什么区别?这些
    都是Java面试中常见的基础问题。面对这样的问题,回答是:ArrayList是非线程安全的,Vector是线程安全的
    ;HashMap是非线程安全的,HashTable是线程安全的;StringBuilder是非线程安全的,StringBuffer是线程安全
    的。因为这是

    昨晚刚背的《Java面试题大全》上面写的。此时如果继续问:什么是线程安全?线程安全和非线程安全有什么
    区别?分别在什么情况下使用?这样一连串的问题,一口老血就喷出来了





    非线程安全的现象模拟



    这里就使用ArrayList和Vector二者来说明。

    下面的代码,在主线程中new了一个非线程安全的ArrayList,然后开1000个线程分别向这个ArrayList里面添加
    元素,每个线程添加100个元素,等所有线程执行完成后,这个ArrayList

    的size应该是多少?应该是100000个?

    复制代码
    1. public class Main  {
    2.        public static void main(String[] args)      {
    3.            // 进行 10次测试  
    4.          for(int i = 0; i < 10; i++)
    5.          {
    6.                test();
    7.           }
    8.       }
    9.              public static void test()      {
    10.           // 用来测试的List     
    11.      List<Object> list = new ArrayList<Object>();   
    12.                   // 线程数量(1000)   
    13.        int threadCount = 1000;   
    14.                  // 用来让主线程等待threadCount个子线程执行完毕     
    15.      CountDownLatch countDownLatch = new CountDownLatch(threadCount);
    16.                    // 启动threadCount个子线程        
    17.   for(int i = 0; i < threadCount; i++)
    18.       {               
    19. Thread thread = new Thread(new MyThread(list,countDownLatch));
    20.                thread.start();
    21.          }   
    22.                   try        {  
    23.              // 主线程等待所有子线程执行完成,再向下执行     
    24.          countDownLatch.await();   
    25.        }
    26.           catch (InterruptedException e)          {
    27.               e.printStackTrace();     
    28.      }                     
    29. // List 的size
    30.          System.out.println(list.size());
    31.      }
    32.   }
    33.      class MyThread implements Runnable  {      
    34. private List<Object> list;
    35.              private CountDownLatch countDownLatch;   
    36.          public MyThread(List<Object> list, CountDownLatch countDownLatch)      {
    37.          this.list = list;
    38.          this.countDownLatch = countDownLatch;   
    39.    }   
    40.           public void run()      {
    41.          // 每个线程向List中添加100个元素      
    42.     for(int i = 0; i < 100; i++)      
    43.    {
    44.              list.add(new Object());   
    45.       }   
    46.                  // 完成一个子线程        
    47.   countDownLatch.countDown();
    48. }
    49. }
    复制代码

    复制代码
    上面进行了10次测试(为什么要测试10次?因为非线程安全并不是每次都会导致问题)。

    输出结果:

    99946

    100000

    100000

    100000

    99998

    99959

    100000

    99975

    100000

    99996

    上面的输出结果发现,并不是每次测试结果都是100000,有好几次测试最后ArrayList的size小于100000,甚至
    时不时会抛出个IndexOutOfBoundsException异常。

    (如果没有这个现象可以多试几次)

    这就是非线程安全带来的问题了。上面的代码如果用于生产环境,就会有隐患就会有BUG了。

    再用线程安全的Vector来进行测试,上面代码改变一处,test()方法中

    1 List<Object> list = new ArrayList<Object>();

    改成

    1 List<Object> list = new Vector<Object>();

    再运行程序。

    输出结果:

    100000

    100000

    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-9 06:22 , Processed in 0.062874 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表