Thread.sleep()不工作.正在跳过操作



这段代码应该搜索网页的html文件,将一些结果打印到窗口,休眠60秒,然后重复搜索。这在python中运行得很好,但翻译成java给我带来了问题。当我尝试执行这个代码时,它不再打印结果,而是无限期地休眠。如果没有while循环,事情似乎是按方面进行的。

btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            running = true;
            while (running) {
                exportField.setText("Searching...");

                try {
                    exportField.setText(crawler.fetchHtml(url););

                } catch (Exception e) {
                    exportField.setText("invalid parameters.");
                    e.printStackTrace();
                }

                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    });

更奇怪的是,如果我尝试像这样简单的东西

exportField.setText("Searching...");
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {              
    e.printStackTrace();
}
exportField.setText("Done Searching");

我希望输出是"searching…"pause"done searching",但事实并非如此。它只是输出"搜索完成"

做这个项目是为了好玩!任何帮助都将不胜感激。

在我看来,您似乎在事件调度线程中。如果是这样的话,你的sleep()会运行得很好——exportField上的重新绘制永远不会发生(在短暂的情况下)或延迟(在简单的睡眠情况下)。

您应该考虑对SwingWorker进行这种长期运行但会改变UI的调用。

一种简化的方法只需启动一个线程并通过SwingUtilities.invokeLater():更新UI

btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            new Thread("Fetcher") {
                boolean running = true;
                public void run() {
                    running = true;
                    while (running) {
                        SwingUtilities.invokeLater(() -> exportField.setText("Searching..."));
                        try {
                            exportField.setText(crawler.fetchHtml(url));
                        } catch (Exception e) {
                            SwingUtilities.invokeLater(() -> exportField.setText("invalid parameters."));
                            e.printStackTrace();
                        }
                        try {
                            Thread.sleep(60000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();              
        }
    });

据我所知,您正在actionPerformed方法中启动一个无限循环(假设运行在某个地方没有设置为false),这将阻止事件调度线程上的所有事件。看看这个挥杆教程。像@Jan所说的长时间运行的事件应该用SwingWorker或至少在上的单独线程上完成

最新更新