ArrayList 线程不安全的体现

ArrayList 线程不安全的体现

标签(空格分隔): j2se


  ArrayList 是线程不安全,主要体现在add时,当只有一个线程时,添加元素时,size++ ,size每次增加1,当有线程A,B,线程A,B添加元素,当size =0 ,当线程A休眠,线程B执行也是从size = 0开始的,这样增加的量就啊2了。

image_1cb6hmefl1j671cbo142kb7b1dle9.png-50.3kB

/**
 * ArrayList线程不安全,体现在,添加元素时
 * @author zenxin
 *
 */
public class ArrayListThread implements Runnable{
    //线程不安全
    private static List<String> list = new ArrayList<>();

       //线程安全  
   /* private  List<String> list = Collections.synchronizedList(new ArrayList());  */
    public static void main(String[] args) {
        ArrayListThread target = new ArrayListThread(); 
        for(int i =1;i<100;i++){
            Thread thread = new Thread(target);
            thread.start();
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         for(int i = 0; i < target.list.size(); i++){  
                if(target.list.get(i) == null){  
                    System.out.println();;  
                }  
                System.out.print(target.list.get(i) + "  ");  
            }  

    }

    @Override
    public void run() {

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    //将当前线程的名字添加到list里面
    list.add(Thread.currentThread().getName());

    }
}

执行结果:
image_1cb6ip0ft19s911rj1ks0j5g151tm.png-20.9kB

猜你喜欢

转载自blog.csdn.net/zx6571269/article/details/79960415