在Java中,Vector和Collections.synchronizedList都是同步的,有什么区别? [英] In java, Vector and Collections.synchronizedList are all synchronized, what's the difference?

查看:43
本文介绍了在Java中,Vector和Collections.synchronizedList都是同步的,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有多个线程访问向量,向量将确保只有一个线程可以同时访问向量.SynchronizedList是相同的.那有什么区别呢?在某些同步情况下如何选择?

If multiple threads access vector, vector will ensure that only one thread can access the vector at the same time. SynchronizedList is same. So what's the difference? How to choose in some synchronous situation?

推荐答案

这种冗余的主要原因是与为旧版本Java开发的Java代码向后兼容.

The main reason for this redundancy is backward compatibility with java code developed for old versions of Java.

如果我没记错的话,Java 1.2 Collections是一个单独的库,不属于标准JDK/JRE.

If I remember correctly before Java 1.2 Collections were a separate library and were not part of standard JDK/JRE.

那时,SDK提供的唯一类似数据结构的列表是Vector.在集合"中,开发人员从许多方面改进了Vector结构.特别是,他们删除了同步,因为在大多数情况下,同步已被证明是不必要的.

At that point the only list like data structure supplied by SDK was Vector. In Collections developers improved that Vector structure in many ways. Particularly, they removed synchronization as it proved to be unnecessary in most of the cases.

他们仍然希望提供一种简单的方法来创建列表(如collection)的同步版本.因此,他们引入了SynchronizedList.

Still they wanted to allow an easy way to create a synchronized version of list like collection. Thus they introduced SynchronizedList.

Vector和SynchronizedList之间的主要区别在于您使用它的方式.通过调用Collections.synchronizedList,您可以在当前的List实现周围创建包装器,这意味着您无需将数据复制到另一个数据结构中,并且可以使基础结构保持完整.例如,如果您想要LinkedList结构而不是ArrayList.

The main difference now between Vector and SynchronizedList is the way you use it. By calling Collections.synchronizedList you create a wrapper around your current List implementation, which means you don't copy data to another data structure and you keep underlying structure intact. For instance, if you want LinkedList structure behind it as opposed to ArrayList.

在使用Vector的情况下,实际上是将数据复制到新的列表中,例如Vector结构.因此,如果以前有一个列表,效率会降低,但是如果以前没有任何数据结构,则可能要使用Vector,因为它不会为每个方法调用增加方法包装成本.向量的另一个缺点是,您不能保留替代的基础结构(例如LinkedList),而是始终使用向量本身实现的内容.

In case of a Vector, you actually copy the data to the new list like structure Vector. So it's less efficient in case you had a list before, but if you didn't have any data structure before, then you may want to use Vector as it doesn't add method wrapping cost to every method invocation. Another disadvantage of a vector is that you can't keep alternative underlying structure (such as LinkedList), you always use what's been implemented in the Vector itself.

这篇关于在Java中,Vector和Collections.synchronizedList都是同步的,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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