Synchronization in Vectors in Java(Java中向量的同步)
问题描述
在Java中vector是什么意思是线程安全和同步的,它是如何做到线程安全的.我正在查看实施的内部细节
what is meant by vector in Java is thread safe and synchronized, how is it made thread safe. I'm looking at internal details of implementation
推荐答案
它是线程安全"的,因为它的所有方法都被同步(通过 synchronized 关键字),请参阅 OpenJDK 源代码.
It is made "thread-safe" by merit of all its methods being synchronized (via the synchronized keyword), see the OpenJDK source code.
synchronized 关键字的作用是防止多个线程同时执行任何同步方法.它在内部使用了一个锁,线程在进入这些方法时必须获得该锁,并且线程在离开该方法时释放.
What the synchronized keyword does is that it prevents more than one thread from executing any of the synchronized methods at the same time. It is using a lock internally, that a thread has to obtain when entering of of those methods, and that the thread releases when it leaves the method.
请注意,这并没有太大帮助,因为虽然它可以防止向量的内部状态不一致,但这并不能保证更高级别的一致性级别(对应用程序有用的级别).
Note that this does not really help much, because while it prevents inconsistent internal state of the vector, this does in no way guarantee a level of consistency on a higher level (a useful level for an application).
考虑这个显示您仍然需要在应用程序代码中使用同步的示例(这样您就可以使用未同步的 ArrayList):
Consider this example that shows that you still need to use synchronization in your application code (so that you might just as well have used the unsynchronized ArrayList):
// BROKEN CODE, needs external synchronization
// only add an element if the vector is empty
if(vector.isEmpty())
vector.add(anElement);
这篇关于Java中向量的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中向量的同步
基础教程推荐
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01