Java中向量的同步

Synchronization in Vectors in Java(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中向量的同步

基础教程推荐