我已经阅读了一些关于同步方法的文章(包括 Oracle 的),但我不确定我是否理解正确。
我有以下代码:
public class Player extends javax.swing.JLabel implements Runnable{
private static int off2[] = {-1, 0, 1, 0}, off1[] = {0, 1, 0, -1};
private static final Map dir = new java.util.HashMap<Integer, Integer>();
static{
dir.put(KeyEvent.VK_UP, 0);
dir.put(KeyEvent.VK_RIGHT, 1);
dir.put(KeyEvent.VK_DOWN, 2);
dir.put(KeyEvent.VK_LEFT, 3);
}
private boolean moving[] = new boolean[4];
@Override
public void run(){
while(true){
for(Object i : dir.values()){
if(isPressed((Integer)i)) setLocation(getX() + off1[(Integer)i], getY() + off2[(Integer)i]);
}
try{
Thread.sleep(10);
}catch(java.lang.InterruptedException e){
System.err.println("Interrupted Exception: " + e.getMessage());
}
}
}
public void start(){
(new Thread(this)).start();
}
private synchronized boolean isPressed(Integer i){
if(moving[i]) return true;
else return false;
}
public synchronized void setPressed(KeyEvent evt) {
if(dir.containsKey(evt.getKeyCode()))moving[(Integer)dir.get(evt.getKeyCode())] = true;
}
public synchronized void setReleased(KeyEvent evt){
if(dir.containsKey(evt.getKeyCode()))moving[(Integer)dir.get(evt.getKeyCode())] = false;
}
}
现在它所做的只是运动。我的理解是当我的主窗体的键侦听器注册 keyPressed 和 Released 事件时,从主线程调用 setPressed 和 setReleased。这段代码合理吗?是否正确使用了 synchronized 关键字?(代码没有它也能工作,但我怀疑最好有它?)