java定时器的问题,在一个新的线程中使用

2025-05-08 11:50:25
推荐回答(1个)
回答1:

相信你的意思是 runnable 为何只执行一次而不是周期性地执行。

你看看 timerExec 方法的文档:
public void timerExec(int milliseconds, Runnable runnable)
Causes the run() method of the runnable to be invoked by the user-interface thread after the specified number of milliseconds have elapsed.

没说是周期性地执行 runnable。

你要周期性执行的话,最直接的方法是在你的 runnable 的 run 方法尾部调用 timerExec。比如:

import org.eclipse.swt.widgets.*;

class C {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);

final int 周期 = 1000;
display.timerExec(周期, new Runnable() {
public void run() {
shell.setText("" + new java.util.Date());
display.timerExec(周期, this);
}
});

shell.open();
while ( ! shell.isDisposed())
if ( ! display.readAndDispatch())
display.sleep();
display.dispose();
}
}