同步容器和并发容器1
package com.bjsxt.base.coll012; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; /** * 多线程使用Vector或者HashTable的示例(简单线程同步问题) * @author alienware * 二、线程安全(Thread-safe)的集合对象: Vector 线程安全: HashTable 线程安全: StringBuffer 线程安全: 三、非线程安全的集合对象: ArrayList : LinkedList: HashMap: HashSet: TreeMap: TreeSet: StringBulider: 3 非线程安全的集合 可以通过 Collections.synchronizedXXX(?) 方法来使不是线程安全的变成线程安全,但是源码只是简单的使用 synchronize 进行同步,影响效率,所以JDK1.5之后出现并发类容器。; */ /* * 如果不是线程安全的结合出现复合型的操作会报错: * Exception in thread "线程10" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859) at java.util.ArrayList$Itr.next(ArrayList.java:831) at com.bjsxt.base.coll012.Tickets$1.run(Tickets.java:51) 修改成线程安全的集合就没这个问题 * * */ public class Tickets { public static void main(String[] args) { //初始化火车票池并添加火车票:避免线程同步可采用Vector替代ArrayList HashTable替代HashMap final Vector<String> tickets = new Vector<String>(); //同步 Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>()); for(int i = 1; i<= 1000; i++){ tickets.add("火车票"+i); } // for (Iterator iterator = tickets.iterator(); iterator.hasNext();) { // String string = (String) iterator.next(); // tickets.remove(20); // } for(int i = 1; i <=10; i ++){ new Thread("线程"+i){ public void run(){ for (Iterator iterator = tickets.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //tickets.remove(20); } } }.start(); new Thread("线程"+i){ public void run(){ while(true){ if(tickets.isEmpty()) break; try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "---" + tickets.add("火车票")); } } }.start(); } } }
相关推荐
Hy 2020-11-13
xrslt 2020-11-06
yutian0 2020-10-26
杨树 2020-09-21
zhuyonge 2020-08-01
zhuyonge 2020-07-26
xiaoemo0 2020-07-18
fraternityjava 2020-06-26
luohui 2020-06-26
dxyadc 2020-06-26
luohui 2020-06-21
三动 2020-06-21
fengyun 2020-06-14
fraternityjava 2020-06-14
waitui00 2020-06-14
fraternityjava 2020-06-10
shayuchaor 2020-06-07