日期:2014-05-20  浏览次数:20679 次

ArrayList不是线程安全的,而Vector则是.谁能举一个例子说明这一点?
ArrayList不是线程安全的,而Vector则是.谁能举一个例子说明这一点?

------解决方案--------------------
多运行几次,看看结果的差异;然后把
static ArrayList al = new ArrayList(20);改成
static List al = Collections.synchronizedList(new ArrayList(20));
之后,再运行几次看结果是否仍有差异....

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);
}

}

------解决方案--------------------
我们一般在对这些collections操作时,都是一个一个操作按顺序来的.所以对这个有一点不理解.如果在存入某个元素的同时又去取出另一个元素,会不会出问题就看是不是线程安全了.如果有两个线程或多个线程同时访问一个ArrayList实例,可能会出现错误,导致某些操作无法执行.
------解决方案--------------------
JDK1.5
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
------解决方案--------------------
JDK1.4
试了几次都是这个结果:
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
Press any key to continue...
------解决方案--------------------
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
JDK1.6
------解决方案--------------------
机器速度不同,快的机器估计看不出效果.
不过可以增加线程, 再弄个 thread3 ,thread4, 应该就能看出
------解决方案--------------------
有内部同步机制就是线程安全的,我的理解是这样的。、
ArrayList的效率比vector
Vector的内部元素是来一个建立一个的,
不过反正现在Java有锁了,也无所谓啦,锁一下就是了,而且逻辑也比较好理解。
------解决方案--------------------
JDK1.4
[0, 0, 1, 1, 2, 2, 3, 3, 4, null, 5, 5, 6, 6, 7, null, 8, 8, 9, null]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]

------解决方案--------------------
[0, 0, 1, 1, 2, 3, 2, 4, 5, 3, 6, 7, 4, 8, 9, 5, 6, 7, 8, 9]
[0, 0, 1, 1, 2, 3, 2, 4, 5, 3, 6, 7, 4, 8, 9, 5, 6, 7, 8, 9]