我的Thread.sleep()出现问题

时间:2011-07-12 20:06:47

标签: java multithreading thread-sleep

我正在制作一个简单的视频扑克节目,现在我正在处理用户指定了他想要持有的牌之后执行的操作,并在抽奖后用新牌替换丢弃的牌。我有一个动作,我想在所有替换之间逐个更换卡片,但是使用下面的代码,它将睡眠500毫秒乘以我必须更换的卡片数量然后替换全部卡片一次,而不是按我的要求一次更换一张。非常感谢任何帮助!

Action drawAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int deckPos = 5;

            if((holdValFirst.getText()).equals("HELD")){}
            else{                   
                holdFirst.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
                deckPos++;
                try
                {
                    Thread.sleep(500);              
                }catch (InterruptedException ie){
                    System.out.println(ie.getMessage());
                }
            }
            if((holdValSecond.getText()).equals("HELD")){}
            else{                   
                holdSecond.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
                deckPos++;
                try
                {
                    Thread.sleep(500);              
                }catch (InterruptedException ie){
                    System.out.println(ie.getMessage());
                }               
            }
            if((holdValThird.getText()).equals("HELD")){}
            else{
                holdThird.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
                deckPos++;
                try
                {
                    Thread.sleep(500);              
                }catch (InterruptedException ie){
                    System.out.println(ie.getMessage());
                }                   
            }
            if((holdValFourth.getText()).equals("HELD")){}
            else{                   
                holdFourth.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
                deckPos++;  
                try
                {
                    Thread.sleep(500);              
                }catch (InterruptedException ie){
                    System.out.println(ie.getMessage());
                }               
            }
            if((holdValFifth.getText()).equals("HELD")){}
            else{                                       
                holdFifth.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
                deckPos++;                                  
            }               
        }
    };

1 个答案:

答案 0 :(得分:8)

当您在事件调度线程(EDT)内部睡眠时,GUI将被冻结。每个长时间运行的任务都应该在EDT之外完成,并且所有摆动操作都应该在EDT中完成。

您应该使用SwingWorker在另一个线程中休眠,并每500ms发布一些进度。或者你可以使用javax.swing.Timer每500毫秒发射一次事件。