margual56 margual56 - 3 months ago 10
Java Question

java.lang.NullPointerException in the multithread program

This is the code:

import java.applet.Applet;
import java.awt.Color;`
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

@SuppressWarnings("serial")
public class Pong extends Applet implements Runnable, KeyListener{

final int width = 700, height = 500;

public static int score = 0;

Thread thread;
HumanPaddle p1;
Ball b1;

public void init(){
this.resize(width, height);

this.addKeyListener(this);

thread = new Thread(this);
thread.start();

p1 = new HumanPaddle(1);
b1 = new Ball();
}

public void paint(Graphics g){
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
p1.draw(g);
b1.draw(g);

g.setColor(Color.red);
g.drawString("Score: " + Integer.toString(score), width/2 - 20, 10);

}

public void update(Graphics g){
paint(g);
}

public void run() {
for(;;){

p1.move();
b1.move();

b1.paddleCollision(p1, p1);

if(b1.getX() > width + 10){score++;
}else if(b1.getX() < -10){score--;}

repaint();

try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

public void keyPressed(KeyEvent key) {
if(key.getKeyCode() == KeyEvent.VK_UP || key.getKeyCode() == KeyEvent.VK_W){
p1.setUpAccel(true);
}else if(key.getKeyCode() == KeyEvent.VK_DOWN || key.getKeyCode() == KeyEvent.VK_S){
p1.setDownAccel(true);
}
}

public void keyReleased(KeyEvent key) {
if(key.getKeyCode() == KeyEvent.VK_UP || key.getKeyCode() == KeyEvent.VK_W){
p1.setUpAccel(false);
}else if(key.getKeyCode() == KeyEvent.VK_DOWN || key.getKeyCode() == KeyEvent.VK_S){
p1.setDownAccel(false);
}
}

public void keyTyped(KeyEvent key) {

}

}


The thing is that SOMETIMES, only sometimes, the code fails and shows


"Exception in thread "Thread-3" java.lang.NullPointerException at
Pong.run(Pong.java:48) at java.lang.Thread.run(Unknown Source)"


I know that means there's an error on line 48 Line 48: "p1.move();"

And makes non sense because it is a valid method and only fails sometimes...

Please, I need quick help... Thank you in advance.

Answer

You have a race condition. Because you start your thread in init() before p1 has been initialized, you run the risk that the thread might run before init has the chance to initialize it. You only need move the initialization of p1 and b1 to before the thread start:

...
    p1 = new HumanPaddle(1);
    b1 = new Ball();

    thread = new Thread(this);
    thread.start(); 
}
Comments