So I’m doing this awkward example to understand how threading in Java works.
It’s quite simple actually, however, I can’t seem to get why this gives me a NullPointerException exception when it tries to fire more than 3 threads.
Can you sort it out? Eclipse’s debugger doesn’t help 🙁
Thanks in advance!!
public class Main {
public static void main(String[] args) {
Main boot = new Main();
}
public Main()
{
CoolThread myThread = new CoolThread(1, 2);
Thread t_myThread = new Thread(myThread);
t_myThread.start();
myThread.defineMain(this);
}
public void teste(String tests){
CoolThread myThread = new CoolThread(1, 2);
Thread t_myThread = new Thread(myThread);
t_myThread.start();
}
}
public class CoolThread extends Thread {
int firstNum;
int secondNum;
Main myMain;
/**
* Constructor
* @param firstNum
* @param secondNum
*/
public CoolThread(int firstNum, int secondNum)
{
this.firstNum = firstNum;
this.secondNum = secondNum;
}
public void defineMain(Main myMain)
{
this.myMain = myMain;
}
/**
* Fires the thread.
*/
public void run()
{
try{
int number = 0;
for(;;)
{
int soma = (firstNum+secondNum);
System.out.println("ID: " +Thread.currentThread().getId());
firstNum++;
secondNum++;
number++;
Thread.sleep(100);
if((number % 10) == 0)
{
myMain.teste("The sum is: " + soma);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
By the way, this is the output I get:
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 9
ID: 12
ID: 9
ID: 12
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 12
ID: 9
ID: 9
ID: 12
ID: 9
ID: 14
java.lang.NullPointerException
at my.own.package.CoolThread.run(CoolThread.java:44)
at java.lang.Thread.run(Thread.java:722)
And it goes on creating and killing threads…
You are either calling
myThread.defineMain(...)after starting your thread (inMain) or not callingdefineMain(...)at all (inteste(...)). You need to define main before the thread is running otherwise there is a chance thatmyMainisnullwhen you get to line 44 which I assume is:This is the definition of a thread race condition. Your start code should be:
Never think that the JDK is wrong. That will just kill any debugging and critical thinking that you are using to find your problem. Learn how to use the debugger in eclipse. You can then put a break-point on line 44 and investigate the variables.
Unfortunately in this case you have a threaded program and the debugging is changing the timing of the program and most likely hiding the bug. You might have tried to print out the various objects on line 44 to see which one was
null.Also, as @kurtzbot pointed out, if
CoolThreadextendsThreadthen you can just saynew CoolThread()and thencoolThread.start(). Really what you should be doing is havingCoolThreadimplementRunnableinstead of extendingThread. That’s the better pattern: