多线程程序中的奇怪NullPointerException

时间:2015-09-15 01:13:41

标签: java multithreading nullpointerexception

我正在练习多线程程序并遇到一个非常奇怪的问题。代码如下。当我运行程序时,有时(并非总是)它会抛出java.lang.NullPointerException。我不知道这个问题是怎么发生的。有没有人可以帮我这个?非常感谢你。

import java.util.*;

public class TestCME {
    public static void main(String[] args){
        TestMap tm = new TestMap();
        for(int i = 0;i < 40000 ;i++){
            tm.addCity(i,new City(i * 10));
        }
        RunnableA rA = new RunnableA(tm);
        Thread threadA = new Thread(rA);
        RunnableB rB = new RunnableB(tm);
        Thread threadB = new Thread(rB);

        threadA.start();
        threadB.start();
    }
}
class TestMap{
    Map<Integer,City> cityMap;

    public TestMap(){
        cityMap = Collections.synchronizedMap(new HashMap<Integer,City>());

    }

    public Set<Integer> getAllKeys(){
        return cityMap.keySet();
    }

    public City getCity(int id){
        return cityMap.get(id);
    }

    public void addCity(int id,City city){
        cityMap.put(id,city);
    }

    public void removeCity(int id){
        cityMap.remove(id);
    }
}

class City{
    int area;
    public City(int area){
        this.area = area;
    }
}

class RunnableA implements Runnable{
    TestMap tm;
    public RunnableA(TestMap tm){
        this.tm = tm;
    }
    public void run(){
        System.out.println("Thread A is starting to run......");

        if(tm != null && tm.cityMap != null && tm.cityMap.size() > 0){

            Set<Integer> idSet = tm.getAllKeys();
            Integer[] idArray = idSet.toArray(new Integer[idSet.size()]);
            for(int i = 0;i < idArray.length;i++){
                Integer id = idArray[i];
                City city = tm.getCity(id);
                if(city != null){
                    System.out.println(id + ":" + city.area);
                    /*try{
                        Thread.sleep(1);
                    }catch(Exception e){
                        e.printStackTrace();
                    }*/
                }
            }

        }
    }
}

class RunnableB implements Runnable{
    TestMap tm;
    public RunnableB(TestMap tm){
        this.tm = tm;
    }
    public void run(){
        System.out.println("Thread B is starting to run......");
        /*try{
            Thread.sleep(1);
        }catch(Exception e){
            e.printStackTrace();
        }*/
        System.out.println("Trying to add elements to map....");
        tm.addCity(50,new City(500));
        System.out.println("Done adding.");
        System.out.println("Trying to remove elements from map....");
        tm.removeCity(10);
        tm.removeCity(20);
        tm.removeCity(30);
        tm.removeCity(40);
        System.out.println("Done removing.");
    }
}

异常日志是

Exception in thread "Thread-0" java.lang.NullPointerException
    at RunnableA.run(TestCME.java:69)
    at java.lang.Thread.run(Thread.java:745)

TestCME.java:69位于City city = tm.getCity(id);的{​​{1}}。

0 个答案:

没有答案