日期:2014-05-20  浏览次数:20767 次

谁来举一个List出现线程安全问题的例子?
谁来举一个List出现线程安全问题的例子?

------解决方案--------------------
package org.test.test;

import java.util.ArrayList;
import java.util.List;

public class UnSafeThread extends Thread {
UnSafeObject unSafe;

int dest;

int value;

String id;

public static void main(String[] args) {
UnSafeObject unSafe = new UnSafeObject();
Thread a = new UnSafeThread(unSafe,0,3, "TA ");
Thread b = new UnSafeThread(unSafe,0,33, "TB ");
a.start();
b.start();
}

public UnSafeThread() {
}

public UnSafeThread(UnSafeObject o, int dest, int value,String id) {
unSafe=o;
this.dest=dest;
this.value=value;
this.id=id;
}

public void run() {
unSafe.l.add(dest,value);
System.out.println(id+ "的位置 "+dest+ " 现在设置为 "+value);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
unSafe.l.get(dest);
System.out.println(id+ "的位置 "+dest+ " = "+unSafe.l.get(dest));
}
}

class UnSafeObject {
List l = new ArrayList();;

static UnSafeObject obj = new UnSafeObject();

public UnSafeObject() {
}

}

------解决方案--------------------
unSafe.l.add(dest,value); == > unSafe.l.add(dest, new Integer(value));
------解决方案--------------------
晕,你有没有意识。有没有想过为啥用sleep

重写了个例子,再看不懂的话建议你转专业去了

package org.test.test;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

public class UnSafeThread <E> extends Thread {
List v;
int id;

public static void main(String[] args) {

List l = new AbstractList() {
public String get(int i) {
return " ";
}

public void add(int index, Integer element) {
}

public String remove(int index) {
if (index == 24) {
System.out.println( "正在删除 " + index + "个元素 ");
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "删除 " + index + "个元素结束 ");
}
if (index == 23) {
System.out.println( "正在删除 " + index + "个元素 ");
System.out.println( "删除 " + index + "个元素结束 ");
}
return " ";
}

public int size() {
return 0;
}

};
List l2 = Collections.synchronizedList(l);
Thread ta = new UnSafeThread(l, 1);
Thread tb = new UnSafeThread(l, 2);
ta.start();
tb.start();
}

public UnSafeThread(List o, int id) {
v = o;
this.id = id;
}

public void run() {
if (id == 1) {
v.remove(24);

} else {
v.remove(23);

}

}
}


------解决方案--------------------
我用sleep(1)直接制造不安全室时刻的状况。

(像你那种用while撞大运的写法要找到那一年去阿)

并且我通过继承一个abstractlist定制了一个list。

用输出信息举了一个多线程remove时候的不安全的过程