Java 集合线程安全

Wesley13
• 阅读 740

线程不安全的的集合有(HashSet,TreeSet,ArrayList,ArrayDeque,LinkedList,HashMap,TreeMap);

线程安全的集合有(Vector,HashTable);

Java给你的保证的线程安全,是说它的方法是执行是排它的,而不是对这个对象本身的多次调用情况下,还是安全的。

1)线程不安全案例:

public class ListThread implements Runnable {  
    String name;  
    List<String> l; 
  
    ListThread(String name, List<String> l) {  
        this.name = name;  
        this.l = l;  
    }  
  
    public void run() {  
        System.out.println(name + "start");  
        for(int i = 0; i<6; i++){
            l.add(name + ".add");  
            System.out.println(name + " list size is " + l.size());  
            try {  
                Thread.sleep(10);  
            } catch(InterruptedException e) {  
                System.out.println(e.getMessage());  
            }  
        }  
    }  
  
    public static void main(String args[]) throws InterruptedException {  
  
        List<String> l = new ArrayList<String>();  
  
        ListThread hello1 = new ListThread("hello1", l);  
        ListThread hello2 = new ListThread("hello2", l);  
        ListThread hello3 = new ListThread("hello3", l);  
  
        Thread h1 = new Thread(hello1);  
        Thread h2 = new Thread(hello2);  
        Thread h3 = new Thread(hello3);  
        h1.start();  
        h2.start();  
        h3.start();  
    }  
}  

执行结果:

hello1start
hello1 list size is 1
hello3start
hello3 list size is 2
hello2start
hello2 list size is 3
hello1 list size is 4
hello3 list size is 5
hello2 list size is 6
hello1 list size is 7
hello2 list size is 9
hello3 list size is 9
hello1 list size is 10
hello3 list size is 11
hello2 list size is 12
hello1 list size is 13
hello3 list size is 14
hello2 list size is 14
hello1 list size is 15
hello3 list size is 17
hello2 list size is 17

----以上结果每个线程执行6次list添加,结果list长度只有17个,数据丢失,线程不安全。

2)线程安全案例:

public class VectorThread implements Runnable {  
    String name;  
    Vector<String> v;  
  
    VectorThread(String name, Vector<String> v) {  
        this.name = name;  
        this.v = v;  
    }  
  
    public void run() {  
        System.out.println(name + "start");  
        for(int i = 0; i<6; i++){
            v.add(name + ".add");  
            System.out.println(name + " vector size is " + v.size());  
  
            try {  
                Thread.sleep(10);  
            } catch(InterruptedException e) {  
                System.out.println(e.getMessage());  
            }  
        }  
    }  
  
    public static void main(String args[]) throws InterruptedException {  
  
        Vector<String> v = new Vector<String>();  
  
        VectorThread hello1 = new VectorThread("hello1", v);  
        VectorThread hello2 = new VectorThread("hello2", v);  
        VectorThread hello3 = new VectorThread("hello3", v);  
  
        Thread h1 = new Thread(hello1);  
        Thread h2 = new Thread(hello2);  
        Thread h3 = new Thread(hello3);  
        h1.start();  
        h2.start();  
        h3.start();  
    }  
}  

执行结果:

hello2start
hello2 vector size is 1
hello3start
hello1start
hello1 vector size is 3
hello3 vector size is 2
hello1 vector size is 5
hello3 vector size is 5
hello2 vector size is 6
hello1 vector size is 7
hello2 vector size is 8
hello3 vector size is 9
hello3 vector size is 12
hello2 vector size is 11
hello1 vector size is 11
hello3 vector size is 14
hello2 vector size is 15
hello1 vector size is 14
hello3 vector size is 17
hello2 vector size is 17
hello1 vector size is 18

--------------线程安全,结果执行无论多少次,最后vector的长度都是18,数据添加完整安全,但是长度在线程抢占时还是有size相同的情况,需要在外围另外添加synchronized

3)外围加锁后的线程安全案例

public class VectorThread2 implements Runnable {  
    String name;  
    Vector<String> v;  
  
    VectorThread2(String name, Vector<String> v) {  
        this.name = name;  
        this.v = v;  
    }  
  
    public void run() {  
        System.out.println(name + "start");  
        
        for(int i = 0; i<6; i++){
            synchronized(v){
                v.add(name + ".add");  
                System.out.println(name + " vector size is " + v.size());  
            }
            try {  
                Thread.sleep(10);  
            } catch(InterruptedException e) {  
                System.out.println(e.getMessage());  
            }  
        }  
    }  
  
    public static void main(String args[]) throws InterruptedException {  
  
        Vector<String> v = new Vector<String>();  
  
        VectorThread2 hello1 = new VectorThread2("hello1", v);  
        VectorThread2 hello2 = new VectorThread2("hello2", v);  
        VectorThread2 hello3 = new VectorThread2("hello3", v);  
  
        Thread h1 = new Thread(hello1);  
        Thread h2 = new Thread(hello2);  
        Thread h3 = new Thread(hello3);  
        h1.start();  
        h2.start();  
        h3.start();  
    }  
}  

执行结果:

hello2start
hello2 vector size is 1
hello2 vector size is 2
hello2 vector size is 3
hello2 vector size is 4
hello1start
hello1 vector size is 5
hello2 vector size is 6
hello1 vector size is 7
hello2 vector size is 8
hello1 vector size is 9
hello3start
hello3 vector size is 10
hello1 vector size is 11
hello3 vector size is 12
hello1 vector size is 13
hello3 vector size is 14
hello1 vector size is 15
hello3 vector size is 16
hello3 vector size is 17
hello3 vector size is 18

----------------------这样无论执行多少次既不会线程抢占,也不会数据丢失

4)使用synchronizedXxx封装后集合线程安全案例(效果和Vector类似)

public class SynchronizedListRight implements Runnable {  
    String name;  
    List<String> list;
  
    SynchronizedListRight(String name, List<String> list) {  
        this.name = name;  
        this.list = list;  
    }  
  
    public void run() {  
        System.out.println(name + "start");  
        
        for(int i = 0; i<6; i++){
            synchronized(list){
                list.add(name + ".add");  
                System.out.println(name + " list size is " + list.size());  
            }
            try {  
                Thread.sleep(10);  
            } catch(InterruptedException e) {  
                System.out.println(e.getMessage());  
            }  
        }  
    }  
  
    public static void main(String args[]) throws InterruptedException {  
  
        List<String> list = Collections.synchronizedList(new ArrayList<String>());
  
        SynchronizedListRight hello1 = new SynchronizedListRight("hello1", list);  
        SynchronizedListRight hello2 = new SynchronizedListRight("hello2", list);  
        SynchronizedListRight hello3 = new SynchronizedListRight("hello3", list);  

        Thread h1 = new Thread(hello1);  
        Thread h2 = new Thread(hello2);  
        Thread h3 = new Thread(hello3);  
        h1.start();  
        h2.start();  
        h3.start();  
    }  
}  

执行结果:

hello3start
hello1start
hello3 list size is 1
hello2start
hello1 list size is 2
hello2 list size is 3
hello1 list size is 4
hello3 list size is 5
hello2 list size is 6
hello1 list size is 7
hello3 list size is 8
hello2 list size is 9
hello2 list size is 10
hello3 list size is 11
hello1 list size is 12
hello2 list size is 13
hello3 list size is 14
hello1 list size is 15
hello1 list size is 16
hello2 list size is 17
hello3 list size is 18

----------效果和第三种案例一样

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
P2P技术揭秘.P2P网络技术原理与典型系统开发
Modular.Java(2009.06)\.Craig.Walls.文字版.pdf:http://www.t00y.com/file/59501950(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fwww.t00y.com%2Ffile%2F59501950)\More.E
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这