看张老师的线程范围内的共享变量,下面一段代码运行有时会出现
空指针异常,分析了半天不知道咋回事。。。- package cn.itcast;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- public class ThreadScopeDataShare {
- private static int data = 0;
- private static Map<Thread, Integer> threadData= new HashMap<Thread, Integer>();
- public static void main(String[] args) {
- for(int i=0; i<2; i++){
- new Thread(new Runnable(){
- @Override
- public void run() {
- int data = new Random().nextInt(9);
- threadData.put(Thread.currentThread(), data);
- System.out.println(Thread.currentThread().getName() + " has " +
- "put data " + data);
-
- new A().get();
- new B().get();
- }
- }).start();
- }
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
- System.out.println(data);
- }
-
- //定义模块A,去获取当前线程的数据data
- static class A {
- int data = threadData.get(Thread.currentThread());
- public void get(){
- System.out.println("A from " + Thread.currentThread().getName()
- + " get data " + data);
- }
- }
-
- //定义模块B,去获取当前线程的数据data
- static class B {
- int data = threadData.get(Thread.currentThread());
- public void get(){
- System.out.println("B from " + Thread.currentThread().getName()
- + " get data " + data);
- }
- }
- }
复制代码 有一次运行结果:- Thread-1 has put data 2
- Thread-0 has put data 1
- A from Thread-0 get data 1
- Exception in thread "Thread-1" java.lang.NullPointerException
- at cn.itcast.ThreadScopeDataShare$A.<init>(ThreadScopeDataShare.java:43)
- at cn.itcast.ThreadScopeDataShare$1.run(ThreadScopeDataShare.java:26)
- at java.lang.Thread.run(Thread.java:662)
- B from Thread-0 get data 1
- 0
复制代码 |