- ArrayList 不是线程安全的集合。如果多个线程可能同时访问和修改ArrayList,可以考虑以下几种方法来解决这个问题:
1、使用线程安全的集合: 使用 CopyOnWriteArrayList 或者 Collections.synchronizedList 包装的 ArrayList。 代码如下:
private final BlockingQueue<List<MBTilesGrid>> rasterContainer = new ArrayBlockingQueue<>(200);
public void processGrids() throws Exception {
while (true) {
List<MBTilesGrid> grids = this.rasterContainer.take();
if (grids != null) {
List<MBTilesGrid> threadSafeGrids = new CopyOnWriteArrayList<>(grids);
// 使用线程安全的集合进行操作
for (MBTilesGrid grid : threadSafeGrids) {
// 处理 grid
}
}
}
}
2、使用显式同步: 在访问和修改集合时使用同步块。 代码如下
private final BlockingQueue<List<MBTilesGrid>> rasterContainer = new ArrayBlockingQueue<>(200);
private final Object lock = new Object();
public void processGrids() throws Exception {
while (true) {
List<MBTilesGrid> grids = this.rasterContainer.take();
if (grids != null) {
synchronized (lock) {
for (MBTilesGrid grid : grids) {
// 处理 grid
}
}
}
}
}
3、使用并发集合框架: 使用 Java 并发包中的集合,例如 ConcurrentHashMap 或者 ConcurrentLinkedQueue。 代码如下:
private final BlockingQueue<List<MBTilesGrid>> rasterContainer = new ArrayBlockingQueue<>(200);
private final ConcurrentLinkedQueue<MBTilesGrid> threadSafeQueue = new ConcurrentLinkedQueue<>();
public void processGrids() throws Exception {
while (true) {
List<MBTilesGrid> grids = this.rasterContainer.take();
if (grids != null) {
threadSafeQueue.addAll(grids);
for (MBTilesGrid grid : threadSafeQueue) {
// 处理 grid
}
}
}
}
附:
ArrayBlockingQueue
是 Java 中一个线程安全的有界阻塞队列,实现了 BlockingQueue 接口。它的容量是固定的,并且在初始化时必须指定。ArrayBlockingQueue 使用数组来存储元素,并且可以在多线程环境下安全地进行并发访问。
主要特点
- 有界:ArrayBlockingQueue 的容量是固定的,不能超过初始化时指定的容量。
- FIFO(先进先出):队列遵循 FIFO 顺序,即先插入的元素先被检索和移除。
- 线程安全:内部使用锁机制来确保多线程环境下的安全性。
- 阻塞操作:提供了阻塞的插入和移除方法,如果队列已满或为空时,调用这些方法的线程会被阻塞,直到队列有空间或元素。