java vector的多线程安全是否有用

vector的使用主要有如下两种场景:
(1)vector所谓的多线程安全,只是针对单纯地调用某个方法它是有同步机制的。如add,多个线程都在对同一个容器add元素,vector能够保证最后总数是正确的,而ArrayList没有同步机制,就无法保证。
(2)vector的多线程安全,在组合操作时不是线程安全的。比如一个线程先调用vector的size方法得到有10个元素,再调用get(9)方法获取最后一个元素,而另一个线程调用remove(9)方法正好删除了这个元素,那第一个线程就会抛越界异常。总结:
(1)在需要对容器进行组合操作时,vector不适用(需要自己用synchronized将组合操作进行同步);
(2)仅在上述第一种场景时,才需要使用vectorpublic class TestMultiThread {private static Vector vec = new Vector();
private static List lst = new ArrayList();public void f() {
TestThread testThread1 = new TestThread();
TestThread testThread2 = new TestThread();
Thread thread1 = new Thread(testThread1);
Thread thread2 = new Thread(testThread2);
thread1.start();
thread2.start();
}public static void main(String[] args) {
TestMultiThread testMultiThread = new TestMultiThread();
testMultiThread.f();

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("vec size is " + vec.size());
System.out.println("lst size is " + lst.size());}private class TestThread implements Runnable { @Override
public void run() {
for (int i = 0; i < 1000; ++i) {
vec.add(i);
lst.add(i);
}
}
private static Vector<Integer> vec = new Vector<Integer>(); private static List<Integer> lst = new ArrayList<Integer>(); public void f() { TestThread testThread1 = new TestThread(); TestThread testThread2 = new TestThread(); Thread thread1 = new Thread(testThread1); Thread thread2 = new Thread(testThread2); thread1.start(); thread2.start(); }  }如上程序运行结果:
vec size is 2000
lst size is 1999

相关内容推荐