I have this class:
`public class Keyboard implements KeyListener {
private boolean[] keys = new boolean[256];
public static boolean UP, LEFT, RIGTH, SHOOT;
public Keyboard() {
UP = false;
LEFT = false;
RIGTH = false;
SHOOT = false;
}
public void update() {
UP = keys[KeyEvent.VK_UP];
LEFT = keys[KeyEvent.VK_LEFT];
RIGTH = keys[KeyEvent.VK_RIGHT];
SHOOT = keys[KeyEvent.VK_P];
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode >= 0 && keyCode < keys.length) {
keys[keyCode] = true;
} else {
System.out.println("Tecla fuera de rango: " + keyCode);
}
}
@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode >= 0 && keyCode < keys.length) {
keys[keyCode] = false;
} else {
System.out.println("Tecla fuera de rango: " + keyCode);
}
}
}`
I understand that the EDT thread would be changing these variables, I see these variables being used in a Player class like this:
public void update() {
...
if (Keyboard.UP) {
acceleration = heading.scale(Constants.ACC);
accelerating = true;
}
...
}
This update() method is called in the GameState class like this:
public void update() {
for (int i = 0; i < movingObjects.size(); i++) {
MovingObject mo = movingObjects.get(i);
mo.update();
...
}
}
this in turn is called in the Windows class (public class Window extends JFrame implements Runnable) like this:
private void update() {
keyboard.update();
State.getCurrentState().update();
}
@Override
public void run() {
...
while (running) {
...
while (delta >= 1) {
update();
draw();
frames++;
delta--;
}
...
}
...
}
Since another thread calls the update method, then should these variables be volatile? If the answer is yes, is there another way to make the keyboard class to not use volatile variables?
pablo fernandez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.