gpt4 book ai didi

java - 通过将函数移至其自己的线程来加速 Java 代码

转载 作者:行者123 更新时间:2023-12-01 13:49:38 26 4
gpt4 key购买 nike

当调用 `Moon m = new Moon(); 时,最底部的以下代码会变慢。为了解决这个问题,我想将以下代码放入线程或其他东西中,以便 MoonCalTimer 更快退出并将值返回给其他函数。知道如何将其放入线程或类似内容中吗?

Moon m = new Moon();
isWaning = m.isWaning();
fullMoon = MoonPhaseFinder.findFullMoonFollowing(Calendar.getInstance());
newMoon = MoonPhaseFinder.findNewMoonFollowing(Calendar.getInstance());

代码:

Timer moonCalTimer = new Timer();
moonCalTimer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
try {

//other code here...
//other code here...
//other code here...

Moon m = new Moon();
isWaning = m.isWaning();
fullMoon = MoonPhaseFinder.findFullMoonFollowing(Calendar.getInstance());
newMoon = MoonPhaseFinder.findNewMoonFollowing(Calendar.getInstance());

}

catch (Exception ex)
{
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}


}
}, 0, 3600000);

最佳答案

您可以将计算包装在 Future 中。然后,您将创建 future 并在自己的线程中启动计算,并将 Future 返回给调用者。这将允许调用者在计算完成之前获得其 Future 结果。

private final ExecutorService pool = Executors.newFixedThreadPool(10);

public Future<Boolean> isWaning(final Moon moon) throws IOException {
return pool.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return moon.isWaning();
}

}
);
}

public Future<Boolean> fullMoonFollowing(final Moon moon) throws IOException {
return pool.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return MoonPhaseFinder.findFullMoonFollowing(Calendar.getInstance());
}

}
);
}

public Future<Boolean> newMoonFollowing(final Moon moon) throws IOException {
return pool.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return MoonPhaseFinder.findNewMoonFollowing(Calendar.getInstance());
}

}
);
}

关于java - 通过将函数移至其自己的线程来加速 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20068794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com