简体   繁体   中英

Java Multithreading null pointer exception

I'm working on this program and I keep getting a NullPointerException and I'm not sure why.

//Constructor

public LongTask(SharedResults sharedData,int start, int end)
{
    super("Thread");
    sharedData=this.sharedData;
    start = this.start;
    end=this.end;

}

//Run

public void run() {
    int sum = 0;
    for (int num = start; num<=end;num++)
            {
        sum+=num;

        try {
            Thread.sleep((long)(5000*Math.random()));
            }

            catch (InterruptedException e)
            {}
        sharedData.addToResult(sum);
        }
}
}

I end up getting a NullPointerException error. It looks like my data is not being summed correctly.

Your problem is:

sharedData=this.sharedData;
start = this.start;
end=this.end;

You are assigned the method level variables to have the values of the class level variables. This needs to be the other way around. The way it's written now, your SharedData will always be null because it's never getting assigned in the constructor. So later, when you call

 sharedData.addToResult(sum);

You are calling attempting to call this method on a null object reference, which explains your NullPointerException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM