ArrayList和Vector线程安全问题(新手提问) threadJava
程序员文章站
2024-03-07 12:03:57
...
我有一段关于ArrayLisy和Vector线程安全的代码,如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class SynchronizedCollectionsTest {
static List<Integer> list = new ArrayList<Integer>(20);
static List<Integer> vector = new Vector<Integer>();
public static void main(String[] args) {
Thread thread1 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
list.add(list.size(), i);
vector.add(vector.size(), i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
};
Thread thread2 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
list.add(list.size(), i);
vector.add(vector.size(), i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
};
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(list);
System.out.println(vector);
}
}
现在想请教各位,为什么list中会有null输出?想知道list是如何产生出null的?
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class SynchronizedCollectionsTest {
static List<Integer> list = new ArrayList<Integer>(20);
static List<Integer> vector = new Vector<Integer>();
public static void main(String[] args) {
Thread thread1 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
list.add(list.size(), i);
vector.add(vector.size(), i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
};
Thread thread2 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
list.add(list.size(), i);
vector.add(vector.size(), i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
};
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(list);
System.out.println(vector);
}
}
现在想请教各位,为什么list中会有null输出?想知道list是如何产生出null的?