本帖最后由 不想飞不到 于 2014-9-12 16:05 编辑
视频的这个例子会报异常。
public class ThreadSopeShareData {
private static Map<Thread,Integer> map = new HashMap<Thread,Integer>();
private static int data = 0;
public static void main(String... args) {
for(int x=1;x<=2;x++){
new Thread(new Runnable(){
@Override
public void run() {
int data =new Random().nextInt();
map.put(Thread.currentThread(),data);
System.out.println(Thread.currentThread().getName()+"...."+data);
new A().get();
new B().get();
}
}).start();
}
}
static class A{
public void get(){
int data = map.get(Thread.currentThread());
System.out.println("A form "+Thread.currentThread().getName()
+"...get data :"+data);
}
}
static class B{
public void get(){
int data = map.get(Thread.currentThread());
System.out.println("B form "+Thread.currentThread().getName()
+"...get data :"+data);
}
}
}
里面用的HashMap是线程不安全的,导致试验中会出现丢失数据的情况,严重会报空指针异常,强烈建议改为HashTable或者对其采取同步措施。
|
|