JUC学习-3-不安全的集合类-CopyOnWriteArrayList-CopyOnWriteArraySet-ConcurrentHashMap
不安全的集合类
CopyOnWriteArrayList
/*
* 并发下 ArrayList 是不安全的
* java.util.ConcurrentModificationException 并发修改异常
* 解决方案
* List<String> list = new Vector<>();
* List<String> list = Collections.synchronizedList(new ArrayList<>());
* List<String> list = new CopyOnWriteArrayList<>(); 写入时复制 COW 计算机程序设计领域的一种优化策略
* 多个线程调用的时候 list 读取的时候是固定的, 写入(覆盖)
* 在写入的时候避免覆盖 造成数据问题
* CopyOnWriteArrayList 比 Vector 好在哪里
*
* */
public class ListTest {
public static void main(String[] args) {
// List<String> list = new ArrayList<>();
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 1; i <= 10; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(list);
}, String.valueOf(i)).start();
}
}
}
CopyOnWriteArraySet
/*
* 并发下 HashSet 是不安全的
* 解决方案
* Set<String> set = Collections.synchronizedSet(new HashSet<>()) ;
* Set<String> set = new CopyOnWriteArraySet<>();
* */
public class SetTest {
public static void main(String[] args) throws InterruptedException {
// Set<String> set = new HashSet<>();
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
set.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}
HashSet的底层就是HashMap
ConcurrentHashMap
/*
* 并发下 HashMap 是不安全的
* 解决方案
* Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
* Map<String, String> map = new ConcurrentHashMap<>();
*
* */
public class MapTest {
public static void main(String[] args) {
//new HashMap<>(); 默认等价为 new HashMap<>(16,0.75);
// Map<String, String> map = new HashMap<>();
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
System.out.println(map);
}, String.valueOf(i)).start();
}
}
}
Callable
- 可以有返回值
- 可以抛出异常
- 方法不同 run()/ call()
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// new Thread(new Runnable() {}).start();
// new Thread(new FutureTask()).start();
// new Thread(new FutureTask(Callable)).start();
MyThread myThread = new MyThread();
FutureTask integerFutureTask = new FutureTask(myThread); // 适配类
new Thread(integerFutureTask, "A").start();
new Thread(integerFutureTask, "B").start(); // 结果会被缓存 提升效率
Object o = integerFutureTask.get(); // 获得callable的返回结果 这个方法可能产生阻塞
System.out.println(o);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("call()");
return 1024;
}
}