通过将函数移动到自己的线程来加速java代码

时间:2013-11-19 10:17:54

标签: java multithreading

调用`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); 

2 个答案:

答案 0 :(得分:1)

您可以将计算包装在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());
    }

  }
  );
}

答案 1 :(得分:0)

如果您希望代码继续下去,您可以这样做:

new Thread()
{
    public void run() {
        Moon m = new Moon();
    }
}.start();

如果你想使用m对象,我认为你可能想要的,你应该创建一个实现可运行的新类,传递m然后调用start。