线程安全-同步容器

线程安全-同步容器

ArrayList->Vector、Stack

Vector实现了List接口实际上就是一个数组,和ArrayList非常相似,Vector方法都是被synchronized修饰过的方法

Stack也是一个同步容器,方法也是使用synchronized修饰过,Stack是继承自Vector类的,栈是先进后出

代码实例

//请求总数
    private static int clientTotal=5000;

    //同时并发请求的线程数
    private static int threadTotal=200;


//    private static SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
    public static List list=new Vector();


//    public static int count=0;

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore=new Semaphore(threadTotal);
        final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int count=i;
            executorService.execute(new Runnable() {
                public void run() {
                    try {
                        semaphore.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    update(count);
                    semaphore.release();
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("length:"+list.size());
    }

    private static void update(int i) {
        list.add(i);
    }

注:返回clientTotal是5000,线程安全的

演示Vector在某些情况下会出现安全问题

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

 public static void main(String[] args) {
     for (int i = 0; i < 10; i++) {
         list.add(i);
     }

     while(true){
         Thread thread1=new Thread(new Runnable() {
             @Override
             public void run() {
                 for (int i = 0; i < 10; i++) {
                     list.remove(i);
                 }
             }
         });
         Thread thread2=new Thread(new Runnable() {
             @Override
             public void run() {
                 for (int i = 0; i < 10; i++) {
                     list.get(i);
                 }
             }
         });
         thread1.start();
         thread2.start();
     }
 }

注: 某个线程在某个时刻在执行vertor get方法,两个方法在执行操作顺序不同的情况下,可能出现线程安全问题,在使用同步容器的时候,并不是在所有场合下都能做到线程安全

HashMap->HashTable(key,value不能为null)

HashTable是实现了Map接口,和HashMap相似,但是进行了同步处理,HashTable的key、value不能为null

Collections->synchronizedXXX(List、Set、Map)

Collections类是工具提供的类,提供了对集合排序、查找等方法,提供了synchronized同步方法来创建同步容器类

public static List<Integer> li= Collections.synchronizedList(Lists.newArrayList());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值