| Vector、HashTable: JDK提供的同步容器类 Collections.synchronizedXXX 本质是对相应的容器进行包装 |
| |
| 同步容器类的缺点: |
| 在单独使用里面的方法的时候,可以保证线程安全,但是,复合操作需要额外加锁来保证线程安全 使用Iterator迭代容器或使用使用for-each遍历容器,在迭代过程中修改容器会抛出 |
| ConcurrentModificationException异常。想要避免出现ConcurrentModificationException,就必须在迭代过程持有容器的锁。但是若容器较大,则迭代的时间也会较长。那么需要访问该容器的其他线程将会长时间等待。从而会极大降低性能。 若不希望在迭代期间对容器加锁,可以使用"克隆"容器的方式。使用线程封闭,由于其他线程不会对容器进行修改,可以避免ConcurrentModificationException。但是在创建副本的时候,存在较大性能开销。 toString,hashCode,equalse,containsAll,removeAll,retainAll等方法都会隐式的Iterate,也即可能抛出ConcurrentModificationException |
| CopyOnWrite、Concurrent、BlockingQueue 根据具体场景进行设计,尽量避免使用锁,提高容器的并发访问性。ConcurrentBlockingQueue:基于queue实现的FIFO的队列。队列为空,取操作会被阻塞ConcurrentLinkedQueue,队列为空,取得时候就直接返回空 |
| public class VectorDemo { |
| |
| public static void main(String[] args) { |
| Vector<String> stringVector = new Vector<>(); |
| for (int i = 0; i < 1000; i++) { |
| stringVector.add("demo" + i); |
| } |
| |
| |
| stringVector.forEach(e->{ |
| if (e.equals("demo3")) { |
| stringVector.remove(e); |
| } |
| System.out.println(e); |
| }); |
| |
| |
| Iterator<String> stringIterator = stringVector.iterator(); |
| while (stringIterator.hasNext()) { |
| String next = stringIterator.next(); |
| if (next.equals("demo2")) { |
| stringIterator.remove(); |
| } |
| } |
| |
| |
| for (int i = 0; i < 4; i++) { |
| new Thread(() -> { |
| synchronized (stringIterator) { |
| while (stringIterator.hasNext()) { |
| String next = stringIterator.next(); |
| if (next.equals("demo2")) { |
| stringIterator.remove(); |
| } |
| } |
| } |
| }).start(); |
| } |
| } |
| |
| } |
| public class Demo { |
| |
| public static void main(String[] args) { |
| ArrayList<String> strings = new ArrayList<>(); |
| List<String> stringList = Collections.synchronizedList(strings); |
| } |
| } |
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术