jdk8 ArrayList在并发添加元素的情况下,会丢元素和出现null的情况
public class Test {
private static List list = new ArrayList < > ( ) ;
@SneakyThrows
public static void main ( String [ ] args) {
testArrayList ( ) ;
}
private static void testArrayList ( ) throws InterruptedException {
CountDownLatch latch = new CountDownLatch ( 2 ) ;
new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
for ( int i = 0 ; i < 100_0000 ; i++ ) {
list. add ( "thread1_" + i) ;
if ( i% 10_0000 == 0 ) {
System . out. println ( "thread1 put 10W" ) ;
}
}
System . out. println ( "thread1 end" ) ;
latch. countDown ( ) ;
}
} , "thread one" ) . start ( ) ;
new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
for ( int i = 0 ; i < 100_0000 ; i++ ) {
list. add ( "thread2_" + i) ;
if ( i% 10_0000 == 0 ) {
System . out. println ( "thread2 put 10W" ) ;
}
}
System . out. println ( "thread2 end" ) ;
latch. countDown ( ) ;
}
} , "thread tow" ) . start ( ) ;
latch. await ( ) ;
System . out. println ( "集合的大小:" + list. size ( ) + ",null元素的数量:" + list. parallelStream ( ) . filter ( Objects :: isNull ) . count ( ) ) ;
}
}