(Java)如果不同步,为什么允许HashSet同步使用? [英] (Java) Why is a HashSet allowed to be used synchronously if it is non synchronized?

查看:59
本文介绍了(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同步使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆