Boolean not correctly updating unless you print it

Chr*_*uze 0 java applet swing boolean

So I am making this java applet and I just want to first make sure the key input works correctly before making it more complex. I have no idea why, but when you remove the "System.out.print(needUpdating);" it does not correctly moves the rectangle according to the key input. Could anyone tell me why and how to fix it? This is a total mystery to me.

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;    
import javax.swing.JApplet;    

public class firstApplet extends JApplet implements KeyListener, Runnable {
    final int MOVEAMOUNT = 1;       
    boolean needUpdating;       
    int x,y,dx,dy;      
    Thread runner = null;

    public void init() {
        this.setFocusable(true);            
        needUpdating = false;           
        this.requestFocusInWindow();            
        x=0;            
        y=0;            
        dx=0;           
        dy=0;           
        addKeyListener(this);
    }

    public void stop() {            
    }

    public void start() {
        runner = new Thread(this);          
        runner.start();
    }

    public void paint(Graphics g) {
        System.out.println("x= "+x+" y = "+y);          
        g.drawRect( x, y, 100, 15 );
    }

    @Override
    public void keyPressed(KeyEvent e) {                        
        int key = e.getKeyCode();           
        if(key==KeyEvent.VK_UP) {
            System.out.println("up");
            dy=MOVEAMOUNT;
        }
        else if (key==KeyEvent.VK_DOWN) {
            dy=-MOVEAMOUNT;
        }
        else if (key==KeyEvent.VK_LEFT) {
            dx=-MOVEAMOUNT;
        }
        else if (key==KeyEvent.VK_RIGHT) {
            dx=MOVEAMOUNT;
        }
        // TODO Auto-generated method stub          
        needUpdating = true;            
        System.out.println("needUpdating listening = " +needUpdating);
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        dx=0;
        dy=0;
    }

    @Override
    public void keyTyped(KeyEvent e) {          
    }

    public void processMovement() {
        System.out.println("processing");
        x+=dx;
        y+=dy;
    }

    @Override
    public void run() {
        this.addKeyListener(this);
        while(true) {
            System.out.print(needUpdating);             
            if(needUpdating) {
                processMovement();                  
                repaint();                  
                needUpdating=false;
            }           
        }           
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*nik 5

您的代码未正确同步.更好的说,它根本不同步.但是,System.out.println是一种同步方法,在当今典型的CPU架构中,进入同步块恰好被实现为本机代码级别的内存屏障.这具有使对其他线程可见的布尔值更改的效果.

结论:正确同步你的代码和"神奇"行为将消失.