• java 之前的安全的类回顾,以及以后需要线程安全时使用哪些类


    之前所学习到的线程安全的类:

    StringBuffer:线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。

    Vector:Vector 类可以实现可增长的对象数组。

    Hashtable:此类实现一个哈希表,该哈希表将键映射到相应的值。任何非 null 对象都可以用作键或值。

    1 // 线程安全的类
    2 StringBuffer sb = new StringBuffer();
    3 Vector<String> v = new Vector<String>();
    4 Hashtable<String, String> h = new Hashtable<String, String>();

    之前提过,Vector是线程安全的时候才去考虑的,但是就算要安全,也不使用它。

    那么,我们使用什么呢?用下面这些:

      API 搜索Collections,查看方法

    A:public static <T> Collection<T> synchronizedCollection(Collection<T> c):返回指定 collection 支持的同步(线程安全的)collection。

    B:public static <T> List<T> synchronizedList(List<T> list):返回指定列表支持的同步(线程安全的)列表。

    C:public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m):返回由指定映射支持的同步(线程安全的)映射。

    D:public static <T> Set<T> synchronizedSet(Set<T> s):返回指定 set 支持的同步(线程安全的)set。

    E:public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m):返回指定有序映射支持的同步(线程安全的)有序映射。

    F:public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s):返回指定有序 set 支持的同步(线程安全的)有序 set。

    选B来作为例子:

      之前的线程不安全:

    List<String> list1 = new ArrayList<String>();// 线程不安全

      现在使用B,线程安全的:

    List<String> list2 = Collections.synchronizedList(new ArrayList<String>()); // 线程安全
    何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
  • 相关阅读:
    codevs 3160 最长公共子串
    bzoj1593 [Usaco2008 Feb]Hotel 旅馆
    bzoj1230 [Usaco2008 Nov]lites 开关灯
    洛谷P1558 色板游戏
    洛谷P2253 好一个一中腰鼓!
    洛谷P2345 奶牛集会
    TopCoder SRM420 Div1 500pt RedIsGood
    洛谷P3144 [USACO16OPEN]关闭农场Closing the Farm_Silver
    洛谷P1455 搭配购买
    洛谷P2398 GCD SUM
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5936390.html
Copyright © 2020-2023  润新知