Java多线程篇之List与Collections集合工具类

Collections是一个Java处理集合的强大工具类,可以进排序,对集合进行简单的多线程封装。本章我们将讲解多线程封装接口

Collections的List<T> synchronizedList(List<T> list)类是一个封装list对象的方法,简单点就是专门对list的内部方法synchronized,以达到多线程操作。

用法如下:

public void collectionsSyncListTest() {List<String> list = new ArrayList<>(); // 原始列表,没有多线程保护List<String> syncList = Collections.synchronizedList(list);  //  通过Collections包装类生产一个新的自动synchronized的listsyncList.add("hello");  // add方法被调用的时候会自动synchornized对象list自身,达到多线程操作保护syncList.add("hello");// for-each循环被调用的时候会自动synchornized对象list自身,达到多线程操作保护for (String text : syncList) {System.out.println(text);}syncList.clear();  // clear方法被调用的时候会自动synchornized对象list自身,达到多线程操作保护
}

接下来我们通过具体源码感受一下吧

public static <T> List<T> synchronizedList(List<T> list) {return (list instanceof RandomAccess ?new SynchronizedRandomAccessList<>(list) :new SynchronizedList<>(list));
}static <T> List<T> synchronizedList(List<T> list, Object mutex) {return (list instanceof RandomAccess ?new SynchronizedRandomAccessList<>(list, mutex) :new SynchronizedList<>(list, mutex));
}/*** @serial include*/
static class SynchronizedList<E>extends SynchronizedCollection<E>implements List<E> {private static final long serialVersionUID = -7754090372962971524L;final List<E> list;SynchronizedList(List<E> list) {super(list);this.list = list;}SynchronizedList(List<E> list, Object mutex) {super(list, mutex);this.list = list;}public boolean equals(Object o) {if (this == o)return true;synchronized (mutex) {return list.equals(o);}}public int hashCode() {synchronized (mutex) {return list.hashCode();}}public E get(int index) {synchronized (mutex) {return list.get(index);}}public E set(int index, E element) {synchronized (mutex) {return list.set(index, element);}}public void add(int index, E element) {synchronized (mutex) {list.add(index, element);}}public E remove(int index) {synchronized (mutex) {return list.remove(index);}}public int indexOf(Object o) {synchronized (mutex) {return list.indexOf(o);}}public int lastIndexOf(Object o) {synchronized (mutex) {return list.lastIndexOf(o);}}public boolean addAll(int index, Collection<? extends E> c) {synchronized (mutex) {return list.addAll(index, c);}}public ListIterator<E> listIterator() {return list.listIterator(); // Must be manually synched by user}public ListIterator<E> listIterator(int index) {return list.listIterator(index); // Must be manually synched by user}public List<E> subList(int fromIndex, int toIndex) {synchronized (mutex) {return new SynchronizedList<>(list.subList(fromIndex, toIndex),mutex);}}@Overridepublic void replaceAll(UnaryOperator<E> operator) {synchronized (mutex) {list.replaceAll(operator);}}@Overridepublic void sort(Comparator<? super E> c) {synchronized (mutex) {list.sort(c);}}/*** SynchronizedRandomAccessList instances are serialized as* SynchronizedList instances to allow them to be deserialized* in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).* This method inverts the transformation.  As a beneficial* side-effect, it also grafts the RandomAccess marker onto* SynchronizedList instances that were serialized in pre-1.4 JREs.** Note: Unfortunately, SynchronizedRandomAccessList instances* serialized in 1.4.1 and deserialized in 1.4 will become* SynchronizedList instances, as this method was missing in 1.4.*/private Object readResolve() {return (list instanceof RandomAccess? new SynchronizedRandomAccessList<>(list): this);}
}/*** @serial include*/
static class SynchronizedCollection<E> implements Collection<E>, Serializable {private static final long serialVersionUID = 3053995032091335093L;final Collection<E> c;  // Backing Collectionfinal Object mutex;     // Object on which to synchronizeSynchronizedCollection(Collection<E> c) {this.c = Objects.requireNonNull(c);mutex = this;}SynchronizedCollection(Collection<E> c, Object mutex) {this.c = Objects.requireNonNull(c);this.mutex = Objects.requireNonNull(mutex);}public int size() {synchronized (mutex) {return c.size();}}public boolean isEmpty() {synchronized (mutex) {return c.isEmpty();}}public boolean contains(Object o) {synchronized (mutex) {return c.contains(o);}}public Object[] toArray() {synchronized (mutex) {return c.toArray();}}public <T> T[] toArray(T[] a) {synchronized (mutex) {return c.toArray(a);}}public Iterator<E> iterator() {return c.iterator(); // Must be manually synched by user!}public boolean add(E e) {synchronized (mutex) {return c.add(e);}}public boolean remove(Object o) {synchronized (mutex) {return c.remove(o);}}public boolean containsAll(Collection<?> coll) {synchronized (mutex) {return c.containsAll(coll);}}public boolean addAll(Collection<? extends E> coll) {synchronized (mutex) {return c.addAll(coll);}}public boolean removeAll(Collection<?> coll) {synchronized (mutex) {return c.removeAll(coll);}}public boolean retainAll(Collection<?> coll) {synchronized (mutex) {return c.retainAll(coll);}}public void clear() {synchronized (mutex) {c.clear();}}public String toString() {synchronized (mutex) {return c.toString();}}// Override default methods in Collection@Overridepublic void forEach(Consumer<? super E> consumer) {synchronized (mutex) {c.forEach(consumer);}}@Overridepublic boolean removeIf(Predicate<? super E> filter) {synchronized (mutex) {return c.removeIf(filter);}}@Overridepublic Spliterator<E> spliterator() {return c.spliterator(); // Must be manually synched by user!}@Overridepublic Stream<E> stream() {return c.stream(); // Must be manually synched by user!}@Overridepublic Stream<E> parallelStream() {return c.parallelStream(); // Must be manually synched by user!}private void writeObject(ObjectOutputStream s) throws IOException {synchronized (mutex) {s.defaultWriteObject();}}
}

可以这么理解,Collections的synchronizedList实现的功能就是在封装List的public时多加了synchronized锁操作。

Java多线程篇之List与Collections集合工具类相关推荐

  1. 【小白学Java】D26 》》》Collections集合工具类

    [友情链接]---–->Java中的各种集合大汇总,学习整理 [友情链接]----–> collection集合 [友情链接]----–> ArrayList集合及其常用功能 [友情 ...

  2. Java集合篇:Map接口、Map接口的实现类、Collections集合工具类

    目录 一.Map接口 1.1 Map接口概述 1.2 Map接口常用功能 二.Map接口的实现类 2.1 Map实现类之一:HashMap 2.1.1 HashMap概述 2.1.2 HashMap的 ...

  3. 小汤学编程之JAVA基础day11——集合框架:List/Set/Map集合、Collections集合工具类、泛型、TreeMap和TreeSet

    一.集合的特点 二.继承结构图 三.List集合 1.特点     2.ArrayList类     3.LinkedList类     4.两者的对比     5.集合的遍历 四.Set集合 1.特 ...

  4. java list排序工具类_java 之 Collections集合工具类排序

    数组有工具类Arrays,集合也有一个工具类Collections. sort方法: sort(List list):根据其元素natural ordering对制定的列表进行排序 sort(List ...

  5. 【java笔记】Collections集合工具类

    java.utils.Collections是集合工具类,用来对集合进行操作 常用方法: public static<T>boolean addAll(Collection<T> ...

  6. java.util.list源码_关于fest-util源码包Collections集合工具类过滤、判空、格式化及复制克隆处理...

    一.前言 关于fest-util源码包org.fest.util.Collections集合处理类,实现对数组转换List序列集合.集合duplicatesFrom克隆复制.集合判空isEmpty.并 ...

  7. Collections集合工具类的方法_sort(List,Comparator)

    简述Comparable和Comparator两个接口的区别. Comparable:强行对实现它的每个类的对象进行整体排序.这种排序被称为类的自然排序,类的compareTo方法被称为它的自然比较方 ...

  8. Collections集合工具类的方法_sort(List)

    Comparator比较器 我们还是先研究这个方法 public static <T> void sort(List<T> list):将集合中元素按照默认规则排序. 不过这次 ...

  9. Collections集合工具类的方法_addAllshuffle

    Collections 常用功能 java.utils.Collections是集合工具类,用来对集合进行操作.部分方法如下: public static <T> boolean addA ...

  10. 18.集合框架(Map集合,HashMap和Hashtable的区别,Collections(集合工具类),集合练习,模拟斗地主(洗牌,发牌,看牌))

    1.Map集合概述和特点 1.需求:    根据学号获取学生姓名 2.Map接口概述     查看API可以知道:     将键映射到值的对象     一个映射不能包含重复的键     每个键最多只能 ...

最新文章

  1. 【Android 逆向】类加载器 ClassLoader ( Android 的八种类加载器 | ClassLoader | BaseDexClassLoader | DexClassLoader )
  2. 在QGraphicsView中拖动QGraphicsWidget
  3. C#using static
  4. [蓝桥杯2019初赛]矩形切割-找规律
  5. Vuejs开发环境搭建及热更新
  6. vue中webpack默认配置_webpack中Entry与Output的基础配置
  7. 使用Pass提高效率
  8. java的反射和它的类加载机制
  9. C#中图片单击旋转事件
  10. AS3 键盘的事件与实现
  11. python解题工程力学_工程力学学习与解题指导
  12. 用户登陆问题,session.invalidate销毁session
  13. 苹果wifi测试中文软件,WiFi测评大师
  14. 微信小程序获取用户手机号
  15. 【你可能不知道的】 PICkit3 脱机烧写 program to go 模式
  16. dsolve函数的功能_为什么Mathematica的DSolve函数会解不出显式解??
  17. 洛谷【P1359】租用游艇
  18. 阅读文献Performance Gains in V2X Experiments Using Distributed Simulation in the Veins Framework
  19. 【高效程序员系列】3、别碰鼠标------让键盘飞起来
  20. java pdf域插入img_java实现在pdf模板的指定位置插入图片

热门文章

  1. msf拿shell后中文乱码解决
  2. 24.两两交换链表中的节点(力扣leetcode) 博主可答疑该问题
  3. mysql架构 三级主从同步_MySQL 主从同步架构中你不知道的“坑”(完结篇)
  4. java隐式参数的作用_隐式参数_scala教程_田守枝Java技术博客
  5. kuka机器人齿轮箱油_库卡KUKA机器人保养润滑油00-144-898
  6. Windows安装zookeeper和kafka
  7. 01 Oracle 导入SQL文件
  8. 第 7 章 Neutron - 073 - Service Plugin / Agent
  9. Selenium Grid
  10. C#匿名委托,匿名函数,lambda表达式