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

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值