java Collections学习

本文深入探讨了Java集合的同步机制,包括使用Collections.synchronizedList、synchronizedSet、synchronizedSortedSet和synchronizedMap的方法,以及如何正确地在同步块中使用迭代器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java集合的同步:(还需深入)

Collections.synchronizedList(List)

List list = Collections.synchronizedList(new ArrayList());

… …

Synchronized(list){

     Iterator i = list.iterator();//Must be in synchronized block

     While(i.hasNext())

          foo(i.next());

}

Collections.synchronizedSet(Set)

Set s = Collections.synchronizedSet(new HashSet());

      ...

  synchronized(s) {

      Iterator i = s.iterator(); // Must be in the synchronized block

      while (i.hasNext())

          foo(i.next());

  }

SortedSet s = Collections.synchronizedSortedSet(new HashSortedSet());

      ...

  synchronized(s) {

      Iterator i = s.iterator(); // Must be in the synchronized block

      while (i.hasNext())

          foo(i.next());

  }

SortedSet s = Collections.synchronizedSortedSet(new HashSortedSet());

  SortedSet s2 = s.headSet(foo);

      ...

  synchronized(s) {  // Note: s, not s2!!!

      Iterator i = s2.iterator(); // Must be in the synchronized block

      while (i.hasNext())

          foo(i.next());

  }

Collections.synchronizedMap(Map)

Map m = Collections.synchronizedMap(new HashMap());

      ...

  Set s = m.keySet();  // Needn't be in synchronized block

      ...

  synchronized(m) {  // Synchronizing on m, not s!

      Iterator i = s.iterator(); // Must be in synchronized block

      while (i.hasNext())

          foo(i.next());

  }

SortedMap m = Collections.synchronizedSortedMap(new HashSortedMap());

      ...

  Set s = m.keySet();  // Needn't be in synchronized block

      ...

  synchronized(m) {  // Synchronizing on m, not s!

      Iterator i = s.iterator(); // Must be in synchronized block

      while (i.hasNext())

          foo(i.next());

  }

SortedMap m = Collections.synchronizedSortedMap(new HashSortedMap());

  SortedMap m2 = m.subMap(foo, bar);

      ...

  Set s2 = m2.keySet();  // Needn't be in synchronized block

      ...

  synchronized(m) {  // Synchronizing on m, not m2 or s2!

      Iterator i = s.iterator(); // Must be in synchronized block

      while (i.hasNext())

          foo(i.next());

  }

 

摘自:http://blog.youkuaiyun.com/qinjienj/article/details/7684340

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值