欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程之集合类

程序员文章站 2022-05-29 13:28:41
...

 

  CopyOnWriteArrayList 

  ConcurrentHashMap

  CopyOnWriteArraySet

 

 public class SynCollectionTest {

 //1.同步list: 每个线程都添加一个元素,看总数
 private CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); //线程安全
 //private List<String> list = new ArrayList<String>(); //线程不安全、会报错
 
 public static void main(String[] args) {
  SynCollectionTest o = new  SynCollectionTest();
  for(int i=0;i<100;i++) {
   o.new ListThread().start();
  }
 }

 class ListThread extends Thread{
  
  public void run() {
   list.add("str");
   System.out.println(list.size());
  }
 }
}

public class SynMapTest {
 
 private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); //线程安全,键、值不能为空值
 //private Hashtable<String, Integer> map = new Hashtable<String, Integer>(); //线程不安全
 //private HashMap<String, Integer> map = new HashMap<String, Integer>(); //线程不安全,抛出异常

 public static void main(String[] args) {
  SynMapTest o = new SynMapTest();
  for(int n=0;n<1000;n++) {
   o.map.put("s"+n, new Integer(0));
  }
  //并发删除,抛出异常 java.util.ConcurrentModificationException
  for(int i=0;i<10;i++) {
   o.new MapThread().start();
  }
 }

 class MapThread extends Thread{
  public void run() {
   Set<String> keys = map.keySet();
   for(String k : keys) {
    map.remove(k);
   }
  }
 }
}

public class SynSet {

 private CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>(); //线程安全
 //private Set<String> set = new HashSet<String>(); //线程不安全,抛出异常java.util.ConcurrentModificationException
 
 private Random r = new Random();
 
 public static void main(String[] args) {
  SynSet o = new SynSet();
  for(int i=0;i<1000;i++) {
   o.set.add(String.valueOf(o.r.nextInt(1000)));
  }
  
  for(int i=0;i<10000;i++) {
   o.new SetThread().start();
  }
 }
 
 class SetThread extends Thread{
  
  public void run() {
   Iterator<String> keys = set.iterator();
   String k = null;
   while(keys.hasNext()) {
    k = keys.next();
    set.remove(k);
   }
  }
 }

}

 

 

 

相关标签: 多线程