Java中延迟函数调用而不暂停应用程序

Mar*_*oni 0 java sleep delay settimeout wait

我希望我的应用程序在标签中显示某些内容几秒钟,然后进行更改。但我不希望我的应用程序在这段时间处于休眠状态。它必须具有功能性。

wait()并使sleep()我的应用程序在此期间无法工作。Java中是否有类似javascript的东西setTimeout(),会继续执行代码并在一段时间后执行一行?

Pio*_*dyl 5

如果您不想包含更复杂的库,您可以使用javax.swing.Timer(如@VGR所述),java.util.concurrent.ScheduledExecutorServicejava.util.Timer.

使用示例javax.swing.Timer

JLabel label = new JLabel("Hello");

Timer timer = new Timer(15000, e -> label.setText("Bye"));

timer.setRepeats(false);
timer.start();
Run Code Online (Sandbox Code Playgroud)

使用示例ScheduledExecutorService(请记住,涉及 UI 组件的实际逻辑可能必须从 GUI 线程(在 Swing 的情况下为 AWT 事件调度线程)运行,而不是执行程序的线程):

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
JLabel label = new JLabel("Hello");

Runnable task = () -> SwingUtilities.invokeLater(() -> label.setText("Bye"));

executor.schedule(task, 15, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

执行器运行后台线程,因此当您不再需要它时应该将其关闭。