List<Integer> contacts = new Vector<Integer>();
Collections.sort(contacts);
好吧,我知道 vector 是线程安全的,但是如果我执行上述操作,会出现任何问题吗?
最佳答案
vector is thread safe
它的每个方法都是线程安全的。但是 Collections.sort 将迭代 vector ,这不是原子操作。特别是Vector's javadoc状态:
if the vector is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
因此,如果您的 vector 在排序时被另一个线程修改,您将收到异常。
如果多个线程可以访问您的结构,则替代方案包括:制作防御性副本或使用并发结构(例如 CopyOnWriteArrayList)。
关于java - java线程安全-集合/列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13404145/