我有一个侦听动作的动作线程。我可以让它在while循环中运行,但是当没有发生移动时,Thread会达到100%的CPU使用率,因为它只是一遍又一遍地通过while循环。
我想要做的是让线程进入睡眠状态 AFTER 它完成它的动画,并在按下按键时将其唤醒
当我按下箭头键时,我会向一个方向移动,直到我松开。 moveThread在此时等待,但当我按下另一个键或相同的键时,keyListener不响应。 Keylistener没有回应,因为当我打电话时
waitMovementThread();
它永远不会离开同步对象。 Idk什么是错的,或者我应该如何解决这种情况。
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();
}
}
答案 0 :(得分:2)
while (true)
或wait()
捆绑在一起。您的GUI将冻结(此时不确定您是否正在执行此操作)。例如,看看this question's answer code,包括camickr's,Trashgod's和我的。