求一个线程安全的set

kolnick 2013-11-11 11:21:45
线程安全的set要用那个

Set set = new HashSet<Player>();
如果使用Set concurrentset=Connections.synchronizedSet(HashSet set)

初始化这个set后是不是就成了线程安全了。
...全文
386 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
teemai 2013-11-11
  • 打赏
  • 举报
回复
看下API,是的: public static <T> Set<T> synchronizedSet(Set<T> s) Returns a synchronized (thread-safe) set backed by the specified set. In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set. It is imperative that the user manually synchronize on the returned set when iterating over it: Set s = Collections.synchronizedSet(new HashSet()); ... synchronized (s) { Iterator i = s.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); } Failure to follow this advice may result in non-deterministic behavior. The returned set will be serializable if the specified set is serializable. Parameters: s - the set to be "wrapped" in a synchronized set. Returns: a synchronized view of the specified set.
kolnick 2013-11-11
  • 打赏
  • 举报
回复
谢谢你们的回答
steely_chen 2013-11-11
  • 打赏
  • 举报
回复
貌似迭代的时候还是要显示的使用synchronized才能让数据达到线程安全。而且此方法返回的只是一个视图(猜测跟复本差不多的东西) public static <T> Set<T> synchronizedSet(Set<T> s)返回指定 set 支持的同步(线程安全的)set。为了保证按顺序访问,必须通过返回的 set 完成对所有底层实现 set 的访问。 在返回的 set 上进行迭代时,用户必须手工在返回的 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()); } 不遵从此建议将导致无法确定的行为。 如果指定 set 是可序列化的,则返回的 set 也将是可序列化的。 参数: s - 被“包装”在同步 set 中的 set。 返回: 指定 set 的同步视图。
raistlic 2013-11-11
  • 打赏
  • 举报
回复
没有“线程安全的set”这种东西。

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧