Hi,
I am creating a simple game and I my game thread and my player2 thread seem to be executing twice each time the Thread.Sleep() expires.
This is the output:
Starting game:
Player 2 thread
Game thread
Starting game:
Player 2 thread
Game thread
Player 2 thread
This is the code:
public class Main extends JComponent implements KeyListener {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.decode("#659D32"));
g.fillRect(0, 0, getHeight(), getWidth());
}
public static void main(String args[]) {
Main g = new Main();
g.createAndShowGUI();
}
public Main() {
setFocusable(true);
addKeyListener(this);
System.out.println("Starting game:");
startGameloop();
}
public void startGameloop() {
Thread t = new Thread() {
public void run() {
boolean active = true;
while(active) {
try {
System.out.println("Game thread");
repaint();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread player2Thread = new Thread() {
public void run() {
boolean activev = true;
while(activev) {
try {
System.out.println("Player 2 thread");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
player2Thread.start();
t.start();
}
public void createAndShowGUI() {
JFrame frame = new JFrame("Graphics");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Main());
frame.setSize(400,200);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
Thanks to anyone who can tell me why!