Java线程安全和非线程安全

原博地址:https://blog.csdn.net/xiao__gui/article/details/8934832
非线程安全的现象模拟

这里就使用ArrayList和Vector二者来说明。

首先先看下以下代码,开启1000个线程,同时调用ArrayList的add方法,每个线程向ArrayList中添加100个数字,如果程序正常执行的情况下应该是输出:

list size is :10000  
public class ThreadSafety {

    private static List<Integer> list = new ArrayList<>();

    private static ExecutorService executorService = Executors.newFixedThreadPool(1000);

    private static class IncreaseTask extends Thread {
        @Override
        public void run() {
            System.out.println("ThreadId:" + Thread.currentThread().getId() + " start!");
            for (int i = 0; i < 100; i++) {
                list.add(i);
            }
            System.out.println("ThreadId:" + Thread.currentThread().getId() + " finished!");
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            executorService.submit(new IncreaseTask());
        }
        executorService.shutdown();
        while (!executorService.isTerminated()) {
            try {
                Thread.sleep(1000 * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("All task finished!");
        System.out.println("list size is :" + list.size());
    }
}

当执行此main方法后,输出如下:

......
ThreadId:2003 start!
ThreadId:2003 finished!
ThreadId:2005 start!
ThreadId:2005 finished!
ThreadId:2009 start!
ThreadId:2009 finished!
ThreadId:2007 start!
ThreadId:2007 finished!
ThreadId:2013 start!
ThreadId:2013 finished!
ThreadId:2011 start!
ThreadId:2011 finished!
All task finished!
list size is :99995

从以上执行结果来看,最后输出的结果会小于我们的期望值。即当多线程调用add方法的时候会出现元素覆盖的问题。
首先我们看一下add的源码如下:

public boolean add(E e) {
    ensureCapacityInternal(size + 1);
    elementData[size++] = e;
    return true;
}

此方法中有两个操作,一个是数组容量检查,另外就是将元素放入数据中。我们先看第二个简单的开始分析,当多个线程执行顺序如下所示的时候,会出现最终数据元素个数小于期望值。这个方法是非线程安全的。
我们再看看Vector的源码:

    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                                                     + " > " + elementCount);
        }
        ensureCapacityHelper(elementCount + 1);
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        elementData[index] = obj;
        elementCount++;
    }

可以看到,Vector的add方法使用了synchronized进行修饰,加了对象锁,所以是线程安全的。
下面将

private static List<Integer> list = new ArrayList<>();

改成

private static List<Integer> list = new Vector<>();

再运行程序,输出结果:

100000

再多跑几次,发现都是100000,没有任何问题。因为Vector是线程安全的,在多线程操作同一个Vector对象时,不会有任何问题。

再换成LinkedList试试,同样还会出现ArrayList类似的问题,因为LinkedList也是非线程安全的。

二者如何取舍

非线程安全是指多线程操作同一个对象可能会出现问题。而线程安全则是多线程操作同一个对象不会有问题。

线程安全必须要使用很多synchronized关键字来同步控制,所以必然会导致性能的降低

所以在使用的时候,如果是多个线程操作同一个对象,那么使用线程安全的Vector;否则,就使用效率更高的ArrayList。

非线程安全!=不安全

有人在使用过程中有一个不正确的观点:我的程序是多线程的,不能使用ArrayList要使用Vector,这样才安全。

非线程安全并不是多线程环境下就不能使用。注意我上面有说到:多线程操作同一个对象。注意是同一个对象。比如最上面那个模拟,就是在主线程中new的一个ArrayList然后多个线程操作同一个ArrayList对象。

如果是每个线程中new一个ArrayList,而这个ArrayList只在这一个线程中使用,那么肯定是没问题的。

线程安全的实现

线程安全是通过线程同步控制来实现的,也就是synchronized关键字。
在这里,我用代码分别实现了一个非线程安全的计数器和线程安全的计数器Counter,并对他们分别进行了多线程测试。
非线程安全的计数器:

public class Main{
	public static void main(String[] args){
		// 进行10次测试
		for(int i = 0; i < 10; i++){
			test();
		}
	}
	
	public static void test(){
		// 计数器
		Counter counter = new Counter();
		
		// 线程数量(1000)
		int threadCount = 1000;
		
		// 用来让主线程等待threadCount个子线程执行完毕
		CountDownLatch countDownLatch = new CountDownLatch(threadCount);
		
		// 启动threadCount个子线程
		for(int i = 0; i < threadCount; i++){
			Thread thread = new Thread(new MyThread(counter, countDownLatch));
			thread.start();
		}
		
		try{
			// 主线程等待所有子线程执行完成,再向下执行
			countDownLatch.await();
		}
		catch (InterruptedException e){
			e.printStackTrace();
		}
		
		// 计数器的值
		System.out.println(counter.getCount());
	}
}
 
class MyThread implements Runnable{
	private Counter counter;
	
	private CountDownLatch countDownLatch;
	
	public MyThread(Counter counter, CountDownLatch countDownLatch){
		this.counter = counter;
		this.countDownLatch = countDownLatch;
	}
	
	public void run(){
		// 每个线程向Counter中进行10000次累加
		for(int i = 0; i < 10000; i++)
		{
			counter.addCount();
		}
		// 完成一个子线程
		countDownLatch.countDown();
	}
}
class Counter{
	private int count = 0;
	public int getCount(){
		return count;
	}
	public void addCount(){
		count++;
	}
}

上面的测试代码中,开启1000个线程,每个线程对计数器进行10000次累加,最终输出结果应该是10000000。
但是上面代码中的Counter未进行同步控制,所以非线程安全。

输出结果:

9963727
9973178
9999577
9987650
9988734
9988665
9987820
9990847
9992305
9972233

稍加修改,把Counter改成线程安全的计数器:

class Counter{
	private int count = 0;
	public int getCount()	{
		return count;
	}
	public synchronized void addCount()	{
		count++;
	}
}

上面只是在addCount()方法中加上了synchronized同步控制,就成为一个线程安全的计数器了。再执行程序。

输出结果:

10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值