线程安全-同步容器
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());