对list的线程不安全操作
对一个线程不安全的集合进行多线程操作, 并不会破单个元素的完整性, 根据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;
}
@Override
public void run() {
// TODO Auto-generated method stub
no.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;
}
@Override
public void run() {
// TODO Auto-generated method stub
no.add(i);
}
}
}
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}