Mar*_*oni 0 java sleep delay settimeout wait
我希望我的应用程序在标签中显示某些内容几秒钟,然后进行更改。但我不希望我的应用程序在这段时间处于休眠状态。它必须具有功能性。
wait()并使sleep()我的应用程序在此期间无法工作。Java中是否有类似javascript的东西setTimeout(),会继续执行代码并在一段时间后执行一行?
如果您不想包含更复杂的库,您可以使用javax.swing.Timer(如@VGR所述),java.util.concurrent.ScheduledExecutorService或java.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)
执行器运行后台线程,因此当您不再需要它时应该将其关闭。
| 归档时间: |
|
| 查看次数: |
1591 次 |
| 最近记录: |