繁体   English   中英

Java启动线程问题

[英]Java- starting thread issue

这是我的简单代码的一部分。此代码包含可移动的椭圆形和静态椭圆形,坐标为newX=100,newY=100试图实现在按下鼠标左键后自动移动该可移动椭圆形的功能。移动代码行在新的Thread thread .Thrad实际上是从单击鼠标按钮开始的,但是什么也没发生。仅在使用箭头键进行了一次移动之后,椭圆形便开始移动。我尝试在不同的地方调用repaint()方法,但这似乎没有帮助。有什么建议吗? 谢谢!

public class Buffer extends JPanel implements Runnable,KeyListener,MouseListener{
public static int x;
public static int y;
public static int newX;
public static int newY;
public static Thread thread;
public static boolean check;
public static JFrame frame;
public static int pointX;
public static int pointY;
public static boolean repaint;


public void paintComponent(Graphics g){
    super.paintComponent(g);

    g.drawOval(x, y, 20, 20);

        newX=100;
        newY=100;
        g.fillOval(newX, newY, 20, 20);

        if(repaint)
            repaint();
}
public static void main(String args[]){
    Buffer z=new Buffer();
    z.setBackground(Color.white);

    frame=new JFrame();
    frame.setSize(500,500);
    frame.addKeyListener(z);
    frame.addMouseListener(z);
    frame.add(z);
    frame.setVisible(true);
    frame.requestFocusInWindow();

    thread=new Thread(){
        public void run(){
            try{
                for(int i=0;i<=5;i++){
                    x=x+i;
                    repaint=true;
                    thread.sleep(1000);

                }
            }catch(InterruptedException v){System.out.println(v);}
           }
        };

}
public void keyPressed(KeyEvent e){
    if(e.getKeyCode()==KeyEvent.VK_LEFT){
        x=x-10;
        repaint();
    }
    if(e.getKeyCode()==KeyEvent.VK_RIGHT){
        x=x+10;
        repaint();
    }
    if(e.getKeyCode()==KeyEvent.VK_UP){
        y=y-10;
        repaint();
    }
    if(e.getKeyCode()==KeyEvent.VK_DOWN){
        y=y+10;
        repaint();
    }
}

public void mouseClicked(MouseEvent e) {
        thread.start();
    }
}

您正在从一个线程修改共享变量,并从另一个线程读取它们,而没有任何类型的同步。 错了 对共享变量的每次访问都必须以同步方式进行,否则应使用线程安全对象(例如AtomicInteger)。

而且,该线程在循环中修改x值,但从不调用repaint() ,因此面板没有理由重新绘制自身。

我不知道这是否是这里可能的问题,但我将尝试一下:

尝试对xy变量使用AtomicInteger,因为代码不是线程安全的。

您试图跨多个线程访问共享变量,并执行增量操作,该操作不是原子的,因此也不安全。

private static AtomicInteger x = new AtomicInteger(0); //take the initial value that you need

//where you are incrementing the x
x.incrementAndGet();


//where you want to read x
value = x.get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM