这是代码:
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) {
}
}
事情是,有时,代码失败并显示
&#34;线程中的异常&#34;线程-3&#34; java.lang.NullPointerException at Pong.run(Pong.java:48)在java.lang.Thread.run(未知来源)&#34;
我知道这意味着第48行第48行出现错误:&#34; p1.move();&#34;
并且没有意义,因为它是一种有效的方法,有时只会失败......
拜托,我需要快速帮助......先谢谢你。
答案 0 :(得分:5)
你有竞争条件。因为在初始化p1之前在init()中启动线程,所以在init有机会初始化之前,您可能会遇到线程可能运行的风险。您只需要将p1和b1的初始化移动到线程开始之前:
...
p1 = new HumanPaddle(1);
b1 = new Ball();
thread = new Thread(this);
thread.start();
}