Java arraylist线程不安全 vectory 线程安全

来源:互联网 发布:golang mgo 查询 编辑:程序博客网 时间:2024/05/22 01:53

如果你的代码所在的进程中有多个线程在同时运行,而这些线可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。一个线程安全的计数器类的同一个实例对象在被多个线程使用的情况下也不会出现计算失误。很显然可以将集合分为两组,线程安全和非线程安全,Vectore是用同步方法来是实现线程安全的而和他相似的ArrayList是线程不安全的。

验证Arraylist为线程不安全类,vectory为线程安全类:

package com.bh.test;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Vector;/** * 验证ArrayList为线程不安全以及解决方法 * @author microsoft * */public class ArrayListInThread2 {    public ArrayListInThread2() {        ThreadGroup group=new ThreadGroup("testGroup");        MyThread at=new MyThread();        for(int i=0;i<10000;i++){            Thread th=new Thread(group,at,String.valueOf(i));            th.start();        }        while (group.activeCount() > 0) {            try {                Thread.sleep(10);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        System.out.println(at.list0.size());        System.out.println(at.list0.get(0));    }    public static void main(String[] args) {        new ArrayListInThread2();    }    class MyThread implements Runnable {        //List<String> list0=new ArrayList<String>(); //thread not safe        Vector<String> list0=new Vector<String>(); //thread not safe        //List<String> list0=Collections.synchronizedList(new ArrayList<String>()); //thread safe        public void run() {            try {                Thread.sleep((int)(Math.random()*2));            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            list0.add(Thread.currentThread().getName());        }    }}

执行程序发现使用arraylist 的时候每次输出的list的长度会不一样。而collection的每次为都1000.

0 0