我有一个监听运动的运动线程。我可以让它运行 while 循环,但是当没有移动发生时,线程会达到 100% 的 CPU 使用率,因为它只是一遍又一遍地通过 while 循环。
我想做的是在它完成动画后让那个线程进入睡眠状态,并在我按下一个键时唤醒它
当我按下箭头键时,我会朝一个方向移动,直到我松开为止。在这一点上,movementThread 等待,但是当我按下另一个键或同一个键时,keyListener 没有响应。Keylistener 没有响应,因为当我打电话时
waitMovementThread();
它永远不会离开同步对象。我知道出了什么问题,或者我应该如何解决这种情况。
private void keyListeners(){
GlobalObjects.frame.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
//Up = 38
//Down = 40
//Left = 37
//Right = 39
System.out.println("Keypressed");
if(e.getKeyCode() == 16){
player.setPlayerMovementSpeed(3);
}
if(e.getKeyCode() == 38){
notifyMovementThread();
player.setPlayerMovement(1);
}else if(e.getKeyCode() == 40){
notifyMovementThread();
player.setPlayerMovement(2);
}else if(e.getKeyCode() == 37){
notifyMovementThread();
player.setPlayerMovement(3);
}else if(e.getKeyCode() == 39){
notifyMovementThread();
player.setPlayerMovement(4);
}
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 16){
player.setPlayerMovementSpeed(10);
}
if(e.getKeyCode() == 38){
if(player.getPlayerMovement() != 1){
}else{
player.setPlayerMovement(0);
waitMovementThread();
}
}else if(e.getKeyCode() == 40){
if(player.getPlayerMovement() != 2){
}else{
player.setPlayerMovement(0);
waitMovementThread();
}
}else if(e.getKeyCode() == 37){
if(player.getPlayerMovement() != 3){
}else{
player.setPlayerMovement(0);
waitMovementThread();
}
}else if(e.getKeyCode() == 39){
if(player.getPlayerMovement() != 4){
}else{
player.setPlayerMovement(0);
waitMovementThread();
}
}
}
@Override
public void keyTyped(KeyEvent e) {
}
});
}
private void waitMovementThread(){
synchronized(movementThread){
try {
movementThread.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void notifyMovementThread(){
synchronized(movementThread){
movementThread.notify();
}
}