你将如何重构以下代码?

时间:2015-09-20 20:56:19

标签: java scheduledexecutorservice

while(!isRunning){
    now = getSystemTime();
    deltaTime = now - lastTime;
    lastTime = now;
    if(deltaTime >= 1000){
        //do something      
     }
}

这段代码看起来很尴尬。我希望线程能够做某事"每1000个单位的时间,但while循环将在1000个单位时间过去之前无限运行,这浪费了CPU的资源。你觉得我怎么能重构这段伪代码?请注意,"做某事"可能是真的。可能需要超过1000个单位的时间。 PS: 我正在使用java进行编码,并希望用Java解决问题。

4 个答案:

答案 0 :(得分:1)

看看Java scheduled executors。您可以使用名为scheduleAtFixedRate的方法。有一个名为TimeUnit的类,在此方法中用于使某些时段运行。这样做的缺点是你必须创建一个Callable或Runnable的实例,这在我看来有点笨拙

答案 1 :(得分:0)

这里的问题是代码执行busy wait,意味着浪费CPU周期,直到delta大于1秒。

最好只是简单地睡一会儿,并允许其他进程在您的进程无效的情况下利用CPU周期:

while(!isRunning){
    doSomething();
    sleep(1000); // see implementation below
}

...

void sleep(int milli) {
    try {
        Thread.sleep(milli);
    } catch (InterruptedException e) {
        // ignore
    }
}

答案 2 :(得分:0)

首先,我会创建一个函数来跟踪时间,以便代码看起来更干净。其次,如果你在里面睡一觉,那么我们就不会在繁忙的等待中占用CPU时间。你可以有更多的定时部分和更多的计时器变量。

int countTime(int & time){
    now = getSystemTime();
    deltaTime = now - time;
    lastTime = now;
    return deltaTime
}

...

while(!isRunning){
    if(countTime(timer) >= 1000){
        //do something      
    }
    usleep(100000) // sleep so we don't occupy CPU
}

答案 3 :(得分:0)

它会永远运行吗?背景是什么?

尝试这样做:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

final Runnable beeper = new Runnable() {
                public void run() { algorithm something here! }
            };      
final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 1000, 1000, TimeUnit.MILLISECONDS);

也许它可以解决你的问题!

如果您对上面发布的方法有疑问,请查看oracle文档: https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html

相关问题