package five;
import java.util.Vector;
import common.Utils;
/**
* vector 中有七个元素,用七个线程去删除它们 删除操作定义为 int i = vec.size()-1; vec.remove(i); 由于此为
* vector 的复合操作,虽然 vector 的单个操作(一个方法)为原子性线程安全,但复合方法就不能保证了
* size()得到锁,求出size,但此时CPU可能转向其它线程,另外一个线程也求得size,最坏情况下七个线程的size都为6
* 而都要删除6,如果其中一个线程删除了6,另外线程再要删除6时,则会 ArrayIndexOutOfBoundsException
*
* @author len
*
*/
public class Collectionses {
private static Vector<Integer> vec = new Vector<Integer>();
public static void main(String args[]) {
// final Collectionses col = new Collectionses();
vec.add(1);
vec.add(2);
vec.add(3);
vec.add(4);
vec.add(5);
vec.add(6);
vec.add(7);
threadRemove();
Utils.sleep(7);// Main sleep(7),wait all the remove thread done;
System.out.println(vec.size());
}
public static void threadRemove() {
removeThread thread = new removeThread();
Thread t1 = new Thread(thread);
Thread t2 = new Thread(thread);
Thread t3 = new Thread(thread);
Thread t4 = new Thread(thread);
Thread t5 = new Thread(thread);
Thread t6 = new Thread(thread);
Thread t7 = new Thread(thread);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
}
/**
*
* 多线程删除集合
*
*/
static class removeThread extends Thread {
@Override
public void run() {
// removeLastNotSyn(vec);//因为此操作是
// vector中的复合操作(也就是多个vector操作一块),vector只保证了一个操作的原子性,对于复合操作,我们要加客户端锁
removeLast(vec);
}
}
public static void removeLast(Vector<Integer> list) {
synchronized (list) {
int i = list.size() - 1;
Utils.sleep(1);// 睡眠一秒,以让其它线程插入
list.remove(i);
System.out.println(Thread.currentThread().getName() + " remove "
+ i);
}
}
public static void removeLastNotSyn(Vector<Integer> list) {
int i = list.size() - 1;
Utils.sleep(1);// 睡眠一秒,以让其它线程插入
list.remove(i);
System.out.println(Thread.currentThread().getName() + " remove " + i);
}
}
没有加载客户端锁的: