import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class ThreadSafeListExample {
// 使用 Collections.synchronizedList 方法将 ArrayList 包装成线程安全的 List
private static final List<String> threadSafeList = Collections.synchronizedList(new ArrayList<>());
public static void main(String[] args) {
// 添加元素到线程安全的列表中
synchronized (threadSafeList) {
threadSafeList.add("Element 1");
threadSafeList.add("Element 2");
threadSafeList.add("Element 3");
}
// 遍历线程安全的列表
synchronized (threadSafeList) {
for (String element : threadSafeList) {
System.out.println(element);
}
}
}
}
Collections.synchronizedList:这是一个静态方法,它将给定的 List 包装成一个线程安全的 List。这意味着多个线程可以安全地同时访问这个 List,而不会导致数据不一致的问题。
synchronized 块:虽然 Collections.synchronizedList 提供了基本的线程安全性,但在某些情况下(例如迭代操作),仍然需要使用 synchronized 块来确保线程安全。这是因为在迭代过程中,如果其他线程修改了列表,可能会导致 ConcurrentModificationException。
示例代码:在 main 方法中,我们展示了如何向线程安全的列表中添加元素,并通过 synchronized 块确保在遍历时不会发生并发修改问题。
上一篇:java 枚举定义
下一篇:java表达式
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站