ArrayList线程不安全测试

在jdk的介绍中,ArrayList是线程不安全的,指的是多线程情况下会有多个线程同时访问这个对象,导致数据达不到预期。
以下是一个示例:
public class ArrayListUnsyncTest {

private static List list = new ArrayList() ;

public static void main (String[] args) {
( new ArrayListUnsyncTest()).test() ;
}

private void test (){
int threadCount = 1000 ;
CountDownLatch countDownLatch = new CountDownLatch(threadCount) ;

ExecutorService exec = Executors. newFixedThreadPool (threadCount) ;
for ( int i= 0 ; i<threadCount ; i++){
exec.submit( new WorkerRunanble(countDownLatch , String. valueOf (i))) ;
}
try {
countDownLatch.await() ;
} catch (InterruptedException e) {
e.printStackTrace() ;
}
exec.shutdown() ;
//System.out.println(list);
System. out .println( list .size()) ;
}

class WorkerRunanble extends Thread{

CountDownLatch countDownLatch ;
String name ;

public WorkerRunanble (CountDownLatch countDownLatch , String name){
this . countDownLatch = countDownLatch ;
this . name = name ;
}

@Override
public void run () {
List list1 = new ArrayList() ;
for ( int j= 0 ; j< 10 ; j++){
list1.add( name + "_" +j) ;
}
list .addAll(list1) ;
countDownLatch .countDown() ;
}
}

}
这个例子中,最终list的size大小可能不是1000*10这么大,原因是多个线程同时往里面写值,造成数据被覆盖。













猜你喜欢

转载自blog.csdn.net/sjzylc/article/details/79166127