如何同步ArrayList [重复]

问题描述 投票:-3回答:1

是否有可能同步ArrayList?

我有多个线程,他们可以访问ArrayList。因此,如果我将一个元素放入我的列表中,那么同时线程B的列表可以用线程B向线程A填充相同的元素和相同的故事。

我尝试过同步列表,但它不起作用。

java multithreading synchronized
1个回答
0
投票

集合api可用于synchronizedList

synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
It is imperative that the user manually synchronize on the returned list when iterating over it:

  List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized (list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

Failure to follow this advice may result in non-deterministic behavior.
The returned list will be serializable if the specified list is serializable.

Parameters:
list - the list to be "wrapped" in a synchronized list.
Returns:
a synchronized view of the specified list.
© www.soinside.com 2019 - 2024. All rights reserved.