Collections.synchronizedList入门级请教 一直在书看到用Collections.synchronizedList可以起线程安全的作用,但是没有找到反例说明不用这个就会出现错误结果的例子有谁可以给个例子用运行结果来说明不用Collections.synchronizedList就不行? 在线等 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 当多个线程用到collection接口类的时候,如果其中一个线程遍历了在修改了其中的值,例外一个线程在同一个时间访问的话就会出现同步问题 Map 和 Set的例子也行,我只是想弄清楚到底怎样的代码会让Collections.synchronizedXXX表现出作用来 之前看到的一个例子,给出了ArrayList和Vector的区别,多次运行后ArrayList会出现空值如果把static ArrayList al = new ArrayList(20);换成static List al = Collections.synchronizedList(new ArrayList(20));应该就没有这个问题了,你可以试试看。当然,这个例子比较简单,只有添加操作,如果还需要访问的话,按照JDK的记载,还需要在使用到变量的时候加上Synchronized(...),你可以去查下Collections.synchronizedList的用法import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.List;import java.util.Vector;public class synchronizedCollectionTest { static ArrayList al = new ArrayList(20); static Vector vt = new Vector(); public static void main(String[] args) throws Exception { Thread thread1 = new Thread() { public void run() { for (int i = 0; i < 10; i++) { al.add(al.size(),new Integer(i)); vt.add(vt.size(),new Integer(i)); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread2 = new Thread() { public void run() { for (int i = 0; i < 10; i++) { al.add(al.size(),new Integer(i)); vt.add(vt.size(),new Integer(i)); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }; thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println(al); System.out.println(vt); }} Spring中为什么实体类不用注入? hibernate+spring getHibernateTemplate null请教~~~为什么 mysql连接的问题 J2EE新手请进 有没有兴趣 大家一起做个J2EE项目学习学习 查询语句如果来写? javamail的mailbody 求各位高手帮忙,tomcat自动关闭问题!急!急!急!急!急!急!急!急!急!急!急!急!急!急! resin怎样配置oracle的数据源和连接池? hibernate 问题 急!!!! springMVC流程 关于jfreechart的问题(菜鸭问题!) 把几万个对象塞到一个List中。。。。。。。。。。
其中的值,例外一个线程在同一个时间访问的话就会出现同步问题
如果把static ArrayList al = new ArrayList(20);换成static List al = Collections.synchronizedList(new ArrayList(20));应该就没有这个问题了,你可以试试看。
当然,这个例子比较简单,只有添加操作,如果还需要访问的话,按照JDK的记载,还需要在使用到变量的时候加上Synchronized(...),你可以去查下Collections.synchronizedList的用法import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Vector;public class synchronizedCollectionTest { static ArrayList al = new ArrayList(20);
static Vector vt = new Vector(); public static void main(String[] args) throws Exception { Thread thread1 = new Thread() { public void run() {
for (int i = 0; i < 10; i++) {
al.add(al.size(),new Integer(i));
vt.add(vt.size(),new Integer(i));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}; Thread thread2 = new Thread() { public void run() {
for (int i = 0; i < 10; i++) {
al.add(al.size(),new Integer(i));
vt.add(vt.size(),new Integer(i));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}; thread1.start(); thread2.start(); thread1.join();
thread2.join();
System.out.println(al);
System.out.println(vt);
}}