欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

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

来源: javaer 分享于  点击 30206 次 点评:63

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


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

相关文章

    暂无相关文章

用户点评