Using a synchronized keyword in Java

I have read some articles (including Oracle) about synchronized methods, and I'm not sure if I understand this correctly.

I have the following code:

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;
    }
}

Now all he does is move. I understand that setPressed and setReleased are called from the main thread when my main form form listener logs KeyPressed and Released events. Is this code reasonable? Is this the correct use of a synchronized keyword? (The code works without it, but I suspect it's better to have it?)

+3
source share
2 answers

, , , .

, , . Swing (= call setLocation()) , . http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable). Runnable:

private boolean moving[] = new boolean[4];
Runnable dirUpdate = new Runnable() {
  for(Object i : dir.values()){
    if(isPressed((Integer)i)) setLocation(getX() + off1[(Integer)i], getY() + off2[(Integer)i]);
  }
};

:

SwingUtils.invokeLater(dirUpdate);

, , dirUpdate .

, null isPressed(), .

dx dy, -1, 1 0 .

+1

Swing, , , ( [] ), .

, [] setXxx ( ) , .

Java 5, java.concurrent , [], AtomicBoolean.

" ":

  • " " - Map < Integer, Integer > to Map ( - setXxxx())

  • if - :)

Lock ( v. ), isPressed() :

// ...
private Lock movingLock = new ReentrantLock();

private  boolean isPressed(Integer i){
  try {
    movingLock.acquire();
    return moving[i];
  } finally
    movingLock.release();
  }        
}

"" [] setXxx Lock.acquire() release()

+1

All Articles