【问题标题】:How to delay an answer while not freezing the thread? [duplicate]如何在不冻结线程的情况下延迟答案? [复制]
【发布时间】:2020-11-15 19:55:19
【问题描述】:

简单的问题。 Thread.sleep(x) 冻结了整个代码,所以即使是按钮也保持原样(按下未按下)

我想基本上是单击一个按钮,“等待”计算机在 x 时间内完成它的事情,然后输出一些东西。

public class bsp extends JFrame {
DrawPanel drawPanel = new DrawPanel();

public bsp() {
    setSize(600,600);
    JButton Hit = new JButton("Hit him");
    Hit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.println("I hit you back!");
            
        }
    });
    Hit.setSize(80, 30);
    Hit.setLocation(200, 400);
    add(Hit);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    add(drawPanel);
    setVisible(true);

}

private static class DrawPanel extends JPanel {

    protected void paintComponent(Graphics g) {
        
    }
}

public static void main(String[] args) {
    new bsp();

}

}

如您所见,按钮“保持”按下状态,整个程序被冻结。 但我基本上是想模拟“A.I.”在回答之前思考,不要冻结一切。

【问题讨论】:

  • 设置Timer,而不是让线程休眠。

标签: java swing sleep


【解决方案1】:

考虑使用Timer 来防止主线程冻结:

import javax.swing.*;
import java.awt.event.*;

        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
             
            }
        };
        Timer countdown = new Timer(1000 ,task);
        countdown.setRepeats(false);
        countdown.start();

其中 1000 是以毫秒为单位的延迟时间,actionPerformed 函数内部是您的代码在延迟时间设置后执行的位置。

【讨论】:

  • 另外docs.oracle.com/javase/9/docs/api/java/util/concurrent/… 是另一种选择,请参阅 ScheduledExecutorService。
  • 那么如果我使用延迟......我将在哪里实现其他计算?比如说我想在这种延迟仍在发生时添加一个简单的“思考......”?
  • @Razak:这个答案是不正确的,因为暗月推荐了 wrong 计时器。你不应该使用java.util.Timer,因为这会违反 Swing 线程规则,但对于 Swing 程序,请始终使用javax.swing.Timer,也就是“Swing 计时器”。前者会导致您的程序意外和间歇性失败,并出现难以调试的线程错误,而后者将正常工作。
  • 知之甚少确实非常正确
  • 你还没有修正你的答案。 -1。请在回答之前了解如何使用 Swing Timers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多