这就是我想象的问题可能是:
问:我在 GUI 事件线程上有一个回调,它必须每 250 毫秒在同一线程上触发一次操作。我不能在这段时间内阻止 GUI 线程,因为它冻结了 GUI。我能做些什么?
A:使用执行器在 GUI 事件线程上定期触发任务。
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// task to be perform periodically in the GUI Event Thread.
}
});
}
}, 250, 250, TimeUnit.MILLISECONDS);
执行任务的 GUI 线程,但执行等待的后台线程。
我会写一些更像
long time = 0;
while(condition) {
long now = System.nanoTime();
if (now >= time + 200e6) {
// do something
time = now;
}
// do something else
}
在不知道程序的具体要求的情况下,可以将代码读取为。
long time = 0; // a local variable or field as appropriate
// you have a loop around all code of interest at some level
// You could have a GUI event loop which you don't define but it is there.
// at some point your checking code is called.
long now = System.nanoTime();
if (now >= time + 200e6) {
// do something
time = now;
}
这不会等待,因为您不想阻止任何事情。相反,它可以防止代码块的调用间隔小于 200 毫秒。
int i = 0, count = 0;
long start = System.nanoTime();
long time = 0;
while (count < 20) {
long now = System.nanoTime();
if (now >= time + 200e6) {
// do something e.g.
count++;
time = now;
}
// do something else
}
long runTime = System.nanoTime() - start;
System.out.printf("Performed something at %.3f per second%n", (count - 1) * 1e9 / runTime);
印刷
Performed something at 5.000 per second