Java 编写刷新线程的最佳方法
您好,我有一些配置,这些配置将在可配置的时间跨度后刷新。做这件事的最好方法是什么,或者遵循什么就足够了Java 编写刷新线程的最佳方法,java,multithreading,Java,Multithreading,您好,我有一些配置,这些配置将在可配置的时间跨度后刷新。做这件事的最好方法是什么,或者遵循什么就足够了 @Override public void run() { try { while(true){ if (isRefreshNeeded) { refresh() } } }
@Override
public void run()
{
try
{
while(true){
if (isRefreshNeeded) {
refresh()
}
}
}
catch( Exception excep )
{
// Log and report exception
}
}
我建议使用Timer类,这就是它的用途
使用您的代码不是一个好主意,因为它会一直迭代,从而消耗CPU周期。除了在一段时间后使用
计时器
/计时器任务
或更现代的ScheduledExecutorService
/可运行
方法进行刷新之外,您可能应该使用侦听器(又称观察者)模式在更改和刷新之间建立因果关系。
如果您对所发布的代码更熟悉,那么至少应该在
while
循环的末尾使用Thread.sleep()
。java.utl.concurrent的ScheduledExecutorService#scheduleAtFixedRate中有一个最干净的选项
是API文档吗请使用计时器类尝试此操作:
long initialDelay = 100; // In millis
long delay = 1000; // In millis
Timer timer = new Timer("Refresher thread");
timer.schedule(new TimerTask() {
@Override
public void run() {
// code to refresh the configurations
}
}, initialDelay, delay);
试用
我相信它已经足够简化,便于使用