改代码是看张孝祥java并发视频发现的一个问题,该代码是仿照视频敲的代码,但和视频最终源码有点小区别:
package Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadScopShare {
/**
* @param args
*/
private static int data=0;
private static Map<Thread,Integer> threadData=new HashMap();
public static void main(String[] args) {
for(int i=0;i<2;i++){
new Thread(new Runnable(){
@Override
public void run() {
data=new Random().nextInt(); //视频最终源码改正后为: int data=new Random().nextInt();
System.out.println(Thread.currentThread().getName()+
" put data:"+data);
threadData.put(Thread.currentThread(), data);
new A().get(); //报错行
new B().get();
}
}).start();
}
}
static class A{
public void get(){//报错行
int data=threadData.get(Thread.currentThread());
System.out.println("A from:"+Thread.currentThread().getName()+
" get data:"+data);
}
}
static class B{
public void get(){
int data=threadData.get(Thread.currentThread());
System.out.println("B from :"+Thread.currentThread().getName()+
" get data:"+data);
}
}
}
该程序运行结果有时候报空指针异常,,
Thread-0 put data:1298776584
A from:Thread-0 get data:1298776584
Exception in thread "Thread-1" java.lang.NullPointerException
B from :Thread-0 get data:1298776584
at Test.ThreadScopShare$A.get(ThreadScopShare.java:33)
at Test.ThreadScopShare$1.run(ThreadScopShare.java:23)
at java.lang.Thread.run(Thread.java:745)
不明白,,为什么会空指针异常,望解释一下,
|
|