对list的线程不安全操作

来源:互联网 发布:淘宝账号 卖家 买家 编辑:程序博客网 时间:2024/06/05 03:11

对一个线程不安全的集合进行多线程操作, 并不会破单个元素的完整性, 根据java内存模型可知,



public class TestCl {List<Integer> no = Collections.synchronizedList(new ArrayList<>());//List<Integer> no = new ArrayList<>();public static void main(String[] args) throws InterruptedException {TestCl t = new TestCl();for(int i=0;i<10000;i++) {new Thread(t.new InnerThread(i)).start();}TimeUnit.SECONDS.sleep(10);System.out.println(t.no.size());}public  class InnerThread implements Runnable{Integer i;public InnerThread (Integer i) {this.i = i;}@Overridepublic void run() {// TODO Auto-generated method stubno.add(i);}}}

对于同步的list, 输出结果是10000

public class TestCl {//List<Integer> no = Collections.synchronizedList(new ArrayList<>());List<Integer> no = new ArrayList<>();public static void main(String[] args) throws InterruptedException {TestCl t = new TestCl();for(int i=0;i<10000;i++) {new Thread(t.new InnerThread(i)).start();}TimeUnit.SECONDS.sleep(10);System.out.println(t.no.size());}public  class InnerThread implements Runnable{Integer i;public InnerThread (Integer i) {this.i = i;}@Overridepublic void run() {// TODO Auto-generated method stubno.add(i);}}}


对于非同步的list, 输出结果会小于10000, 因为arraylist存在两个全局变量transient Object[] elementData; private int size; 而在多线程执行add方法时, 两个全局变量会出现线程安全问题. 当两个线程同时操作两个全局变量, 如果其中一个线程没有及时将当前缓存的内容刷新到共享内存中, 这个线程最后刷新的时候可能会覆盖其他已经修改的该位置的内容

public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }



原创粉丝点击