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导致删除或者读取都会报错