Is multi-thread safety of java vector useful

I searched a lot of articles on the Internet, and found that there are many that are not clear, and there are many good articles. This article hopes to describe the problem more easily. If there is anything wrong, please correct me~~

The use of vector mainly has the following two scenarios:
(1) The so-called multi-thread safety of vector is only for simply calling a method, which has a synchronization mechanism. Such as add, multiple threads are adding elements to the same container, vector can ensure that the final total is correct, and ArrayList has no synchronization mechanism, so it cannot be guaranteed.
(2) The multi-thread safety of vector is not thread-safe when combining operations. For example, a thread first calls the size method of the vector to get 10 elements, then calls the get(9) method to get the last element, and another thread calls the remove(9) method to just delete this element, then the first thread will Throws an out-of-bounds exception.

Summary:
(1) When the container needs to be combined, vector is not suitable (you need to use synchronized to synchronize the combined operation);
(2) Only in the first scenario above, you need to use vector

public class TestMultiThread {

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

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

 

}

The result of running the above program:
vec size is 2000
lst size is 1999

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324798863&siteId=291194637