【问题标题】:Repeatable start of thread线程的可重复开始
【发布时间】:2013-07-20 12:15:13
【问题描述】:

这段代码包含可移动的吃豆人,它在按下空格键后射出小椭圆。所以布尔变量默认为false。按下空格键后变为真,并绘制椭圆形。按下空格键后,也启动了新线程。该线程包含向前移动椭圆的代码,一旦到达某些坐标,它就会消失。所以当我第一次按空格时,一切正常。实际上,经过多次后它也能正常工作,但 elclipse 不断抛出 IllegalThreadStateException。我决定把线程将代码写入while(c!=22) 块,因为当 c=21 时球消失,所以我认为线程将继续运行,因为无法满足条件。所以我的意思是每次按下空格按钮时使椭圆移动。这不是完整的代码。只是重要的部分。如果您需要完整的代码,请告诉我。谢谢!

线程:

        thread=new Thread(){
        public void run(){
            while(c!=22){
            try{
            for (c=0;c<=20;c++){
                newX=newX+c;
                repaint=true;
                Thread.sleep(100);  
                }
            if(c==21){
                shoot=false;
                c=0;
            }
        }catch(InterruptedException v){System.out.println(v);}
        }
        }
    };

paintComponent 方法:

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

    i=new ImageIcon("C:\\Users\\Jakub\\Desktop\\pm.gif");
    pacman=i.getImage();

    g.drawImage(pacman,x,y,this);

    if(!shoot)
        newX=x+20;
        newY=y+10;

    if(shoot){
    g.drawOval(newX,newY,10,10);
    }

    if(repaint)
        repaint();

}

启动线程的关键事件:

if(e.getKeyCode()==KeyEvent.VK_SPACE){
    shoot=true;
    thread.start();
}

【问题讨论】:

  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2)i=new ImageIcon("C:\\Users\\Jakub\\Desktop\\pm.gif");不要尝试在paint方法中加载资源。而是将它们声明为类属性,并在需要时简单地绘制它们。

标签: java multithreading swing user-interface


【解决方案1】:

IllegalThreadStateException 可能会被抛出,因为您为同一个线程对象多次调用Thread.start()。避免此异常的关键是每次在启动之前实例化thread(具体实现取决于您想要实现的行为)。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2012-07-29
    • 2017-01-30
    • 2018-05-28
    • 1970-01-01
    • 2015-09-02
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多