(Java)如果不同步,为什么允许HashSet同步使用?

编程入门 行业动态 更新时间:2024-10-24 16:29:40
本文介绍了(Java)如果不同步,为什么允许HashSet同步使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在阅读 HashMap , HashSet 和 HashTable 之间的区别.我注意到的关键是,我看到 HashMap / HashSet 在 HashTable 处于同步状态时不同步.

I've been reading up on the differences between a HashMap, HashSet, and HashTable. A key thing I've been noticing is that I've seen that HashMap/HashSet are not synchronized while a HashTable is.

但是,在我之前看到的代码库中,有好几个地方使用了这样的块:

However in a code base that I've seen before there are several places where a block like this is used:

synchronized (hashSet) { //Some code involving the hashset }

如果 HashSet 不同步,怎么办?同步块是否仅允许我们使用非同步数据结构,就好像它已同步一样?

How is this possible if a HashSet isn't synchronized? Does the synchronized block simply allow us to use a non synchronous data structure as if it were synchronized?

如果 HashSet 是同步的,我们是否就不必包含synced(){}块了吗?

If HashSet were synchronized would we just not have to include the synchronized() {} block?

推荐答案

一个 Synchronized 块需要一些对象进行同步.当说 HashSet 是不同步的时,这仅意味着它的方法本身并不同步,如果您打算在多线程上下文中使用它,则应自己处理同步(例如,如代码段所示,通过对 HashSet 对象进行 synchronization ).

A synchronized block requires some object to syncronize upon. When a HashSet is said to be unsynchronized it just means that it's methods aren't synchronized in their own right, and if you intend to use it in a multi-threaded context, you should handle synchronization by yourself (e.g., by synchronizing on the HashSet object as shown in your snippet).

更多推荐

(Java)如果不同步,为什么允许HashSet同步使用?

本文发布于:2023-10-26 19:06:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531082.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不同步   Java   HashSet

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!