ArrayList总结

Vector与List区别?

Vector使用了同步机制,相比之下List的效率更高。

日常生活中List也是使用比较多的,那么如何更好的使用List呢?

如果是要频繁更新list,可以使用CopyOnWriteArrayList

如果考虑线程安全呢?

使用Collections.synchronizedList(new ArrayList<Integer>());

如何体现线程安全习惯呢?

 

举个栗子:

package com.example.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: 大鸡腿
 * @Date: 2019/4/6 20:55
 * @Version 1.0
 */
public class Test3 {
    public static void main(String[] args) {
        List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    int i = (int) (Math.random() * 100);
                    System.out.println("插入" + i);
                    list.add(i);
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
        });
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        System.out.println("删除" + list.remove(0));
                    } catch (Exception e) {
                        continue;
                    }
                }
            }
        });
        thread.start();
        thread1.start();
    }
}

输出:

插入16
删除16
插入37
删除37
插入66
删除66
插入22
删除22
插入92
删除92
插入45
删除45
插入65
删除65
插入76
删除76
插入2
删除2
插入7
删除7
插入14
删除14
插入1
删除1

 

注意一个地方:

                try {
                        System.out.println("删除" + list.remove(0));
                    } catch (Exception e) {
                        continue;
                    }

由于你另一个线程在改变List导致删除或者读取都会报错

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值