1)使用线程安全的Vector进行操作,多线程并发的情况下,一定是线程安全的吗?
答案:不是
原因:虽然Vector的大部分方法都加上了synchronized同步块,但是比如如下需求:
void deleteLastEle(){
int lastIndex = vec.size() - 1; // 1
vec.remove(lastIndex); // 2
}
虽然1和2处都是线程安全的,但是在多线程环境下,1 2联合在一起并不是原子操作,不是线程安全的,多线程下导致索引异常。
Run.java
package VectorTest;
import java.util.Random;
import java.util.Vector;
public class Run implements Runnable {
private Vector v = new Vector();
private Random r = new Random();
public void init() {
for (int i = 0; i < 10; i++) {
v.add(i);
}
}
private void deleteLast() {
int lastIndex = v.size() - 1;
if (lastIndex >= 0) {
System.out.println(lastIndex);
v.remove(lastIndex);
}
}
@Override
public void run() {
deleteLast();
}
}
Main.java
package VectorTest;
public class Main {
public static void main(String[] args) {
Run r = new Run();
r.init();
for (int i = 0; i < 100; i++) {
new Thread(r).start();
}
}
}
/*
9
8
8
7
7
6
5
4
3
2
1
0
Exception in thread "Thread-5" Exception in thread "Thread-15" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 8
at java.util.Vector.remove(Vector.java:831)
at VectorTest.Run.deleteLast(Run.java:22)
at VectorTest.Run.run(Run.java:28)
at java.lang.Thread.run(Thread.java:748)
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 7
at java.util.Vector.remove(Vector.java:831)
at VectorTest.Run.deleteLast(Run.java:22)
at VectorTest.Run.run(Run.java:28)
at java.lang.Thread.run(Thread.java:748)
*/
因此还是要下面这样写才行:
private void deleteLast() {
// 为了原子性,必须加上锁
synchronized (v) {
int lastIndex = v.size() - 1;
if (lastIndex >= 0) {
System.out.println(lastIndex);
v.remove(lastIndex);
}
}
}
这样保证只能有一个线程执行,才行。
/*
9
8
7
6
5
4
3
2
1
0
*/