当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
计算机二级辅导:Java容器类的线程安全
发布时间:2010/3/14 18:40:37 来源:城市学习网 编辑:MOON
  Collection
  ├List 接口
  │├LinkedList 链表
  │├ArrayList 顺序结构动态数组类
  │└Vector 向量
  │└Stack 栈
  └Set
  Map
  ├HashTable
  ├HashMap
  └WeakHashMap List接口
  Vector和HashMap是线程安全的
  LinkedList、ArrayList和HashMap是线程不安全的
  由于同步需要花费时间,因此线程安全的执行效率要低于线程不安全的
  案例:多线程操作导致List报NoSuchElementException
  java.util.NoSuchElementException
  at java.util.LinkedList.remove(LinkedList.java:788)
  at java.util.LinkedList.removeFirst(LinkedList.java:134)
  at freemarker.core.RegexBuiltins.getPattern(RegexBuiltins.java:138)
  解决方法:
  调用Collections的同步List
  ListString items = Collections.synchronizedList(new LinkedListString());
  public void remove() {
  if (!items.isEmpty()) {
  return items.remove(0);
  }
  }
  设置标志,同步
  LinkedListString items = new LinkedListString();
  String flag="abcdef";
  public void remove() {
  synchronized(flag){
  if (!items.isEmpty()) {
  return items.removeFirst();
  }
  }
  :
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved