ArrayList线程不安全
package com.yuzhenc.collection;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test20 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 0; i < 10000; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
arrayList.add("aaa");
}
});
}
executorService.shutdown();
while(true) {
if(executorService.isTerminated()) {
System.out.println("所有子线程都执行完毕!");
if (arrayList.size() == 10000) {
System.out.println("线程安全!");
} else {
System.out.println(arrayList.size());
System.out.println("线程不安全!");
}
break;
}
}
}
}
同步类容器线程安全
package com.yuzhenc.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test21 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
List<String> list = Collections.synchronizedList(arrayList);
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (int i = 0; i < 10000; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
list.add("aaa");
}
});
}
executorService.shutdown();
while(true) {
if(executorService.isTerminated()) {
System.out.println("所有子线程都执行完毕!");
if (list.size() == 10000) {
System.out.println("线程安全!");
} else {
System.out.println(list.size());
System.out.println("线程不安全");
}
break;
}
}
}
}