如何同步ArrayList

时间:2018-01-06 15:38:33

标签: java multithreading synchronized

是否有可能同步ArrayList?

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

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

1 个答案:

答案 0 :(得分:0)

可用于synchronizedList的集合api

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.