为什么名单< T>不是线程安全的?线程、名单、不是、安全

2023-09-02 01:44:14 作者:孤独成性不过是看透人心

从该网站:

http://crfdesign.net/programming/top-10-differences-between-java-and-c

不幸的是,清单和LT;>不   线程安全的(C#的ArrayList和Java的   载体是线程安全的)。 C#也有一个   哈希表;通用版本是:

Unfortunately, List<> is not thread-safe (C#’s ArrayList and Java’s Vector are thread-safe). C# also has a Hashtable; the generic version is:

是什么让名单,其中,T&GT; 不是线程安全的?它是在.NET框架工程的一部分执行的问题?或者是仿制药不是线程安全的?

what makes List<T> not thread-safe? is it implementation problem on .net framework engineer's part? or are generics not thread-safe?

推荐答案

您真的需要进行分类Java的Vector的类型线程安全的。 Java类Vector是安全,可以从多个线程使用,因为它使用的方法同步。国家将不会被破坏。

You really need to classify Java's Vector's type of thread safety. Javas Vector is safe to be used from multiple threads because it uses synchronization on the methods. State will not be corrupted.

不过,Java的载体的有用性从多个线程无需额外的同步限制。例如,考虑从一个vector

However, Java's vector's usefulness is limited from multiple threads without additional synchronization. For example, consider the simple act of reading an element from a vector

Vector vector = getVector();
if ( vector.size() > 0 ) { 
  object first = vector.get(0);
}

这个方法不会破坏载体的状态,但它也是不正确的。尽管没有理由变异的载体中,如果语句中的get()调用之间停止另一个线程。这code能和会终因竞争状态失败。

This method will not corrupt the state of the vector, but it also is not correct. There is nothing stopping another thread from mutating the vector in between the if statement an the get() call. This code can and will eventually fail because of a race condition.

这类型的同步仅在场景一福有用的,这肯定是不便宜。你付出了noticable价格同步,即使你不使用多个线程。

This type of synchronization is only useful in a handfull of scenarios and it is certainly not cheap. You pay a noticable price for synchronization even if you don't use multiple threads.

净选择不支付这样的价格在默认情况下只用处不大的情况下。相反,它选择实施锁空闲列表。作者负责添加任何同步。这是更接近C ++的模式只支付您所使用的

.Net chose not to pay this price by default for a scenario of only limited usefulness. Instead it chose to implement a lock free List. Authors are responsible for adding any synchronization. It's closer to C++'s model of "pay only for what you use"

我最近写了几篇文章上使用集合,只有内部同步,如Java的矢量的危险。

I recently wrote a couple of articles on the dangers of using collections with only internal synchronization such as Java's vector.

为什么是线程安全的集合这么难? 更对一个可变的线程安全集合 可用的API Why are thread safe collections so hard? A more usable API for a mutable thread safe collection

参考向量线程安全: http://www.ibm.com /developerworks/java/library/j-jtp09263.html