Collections.synchronizedList(list) 把一个非线程安全的List转为线程安全的List。

    1. import java.util.ArrayList;
    2. import java.util.Collections;
    3. import java.util.List;
    4. public class Test {
    5. public static void test() {
    6. List list = new ArrayList();
    7. List synchronizedList = Collections.synchronizedList(list);
    8. }
    9. }

    Collections中部分源码

    1. public static <T> List<T> synchronizedList(List<T> list) {
    2. return (list instanceof RandomAccess ?
    3. new SynchronizedRandomAccessList<>(list) :
    4. new SynchronizedList<>(list));
    5. }
    6. static class SynchronizedList<E>
    7. extends SynchronizedCollection<E>
    8. implements List<E> {
    9. private static final long serialVersionUID = -7754090372962971524L;
    10. final List<E> list;
    11. SynchronizedList(List<E> list) {
    12. super(list);
    13. this.list = list;
    14. }
    15. SynchronizedList(List<E> list, Object mutex) {
    16. super(list, mutex);
    17. this.list = list;
    18. }
    19. public boolean equals(Object o) {
    20. if (this == o)
    21. return true;
    22. synchronized (mutex) {return list.equals(o);}
    23. }
    24. public int hashCode() {
    25. synchronized (mutex) {return list.hashCode();}
    26. }
    27. public E get(int index) {
    28. synchronized (mutex) {return list.get(index);}
    29. }
    30. public E set(int index, E element) {
    31. synchronized (mutex) {return list.set(index, element);}
    32. }
    33. public void add(int index, E element) {
    34. synchronized (mutex) {list.add(index, element);}
    35. }
    36. public E remove(int index) {
    37. synchronized (mutex) {return list.remove(index);}
    38. }
    39. public int indexOf(Object o) {
    40. synchronized (mutex) {return list.indexOf(o);}
    41. }
    42. public int lastIndexOf(Object o) {
    43. synchronized (mutex) {return list.lastIndexOf(o);}
    44. }
    45. public boolean addAll(int index, Collection<? extends E> c) {
    46. synchronized (mutex) {return list.addAll(index, c);}
    47. }
    48. public ListIterator<E> listIterator() {
    49. return list.listIterator(); // Must be manually synched by user
    50. }
    51. public ListIterator<E> listIterator(int index) {
    52. return list.listIterator(index); // Must be manually synched by user
    53. }
    54. public List<E> subList(int fromIndex, int toIndex) {
    55. synchronized (mutex) {
    56. return new SynchronizedList<>(list.subList(fromIndex, toIndex),
    57. mutex);
    58. }
    59. }
    60. @Override
    61. public void replaceAll(UnaryOperator<E> operator) {
    62. synchronized (mutex) {list.replaceAll(operator);}
    63. }
    64. @Override
    65. public void sort(Comparator<? super E> c) {
    66. synchronized (mutex) {list.sort(c);}
    67. }
    68. private Object readResolve() {
    69. return (list instanceof RandomAccess
    70. ? new SynchronizedRandomAccessList<>(list)
    71. : this);
    72. }
    73. }

    其实就是用synchronized 同步代码块。