如何修改Scala代码让它停止计算?

时间:2017-06-24 13:33:00

标签: java scala

鉴于我有以下Scala代码:

import java.util.concurrent._

object TimeOutTask {
  def main(args: Array[String]): Unit = {
    val executorService = Executors.newFixedThreadPool(1)
    val futureTask = new FutureTask(
      new Callable[Boolean] {
        override def call(): Boolean = {
          println("calculation begins:")
          val t0 = System.nanoTime: Double
          sum(2000000000)
          val t1 = System.nanoTime: Double
          println("Elapsed time " + (t1 - t0) / 1000000000.0 + " secs")
          true
        }
      })

    try {
      executorService.submit(futureTask).get(5, TimeUnit.SECONDS)
    }
    catch {
      case e: TimeoutException =>
        System.out.println("Time out~~~")
        e.printStackTrace()
        executorService.shutdownNow()
    }
  }

  def sum(k: BigInt): BigInt = {
    var total: BigInt = 0
    for (i <- (1: BigInt) to k) total += i
    total
  }
}

我想将sum()的执行时间保持在5秒以下。但是,我发现executorService.shutdownNow()在测试时无法阻止sum()的执行。

enter image description here

1 个答案:

答案 0 :(得分:1)

sum方法需要知道它应该停止计算总和。 这是可能的,因为executorService将在关闭时尝试中断线程。

sum方法可以检查线程是否中断,如果是,则应该抛出InterruptedException:

  def sum(k: BigInt): BigInt = {
    var total: BigInt = 0
    for (i <- (1: BigInt) to k) {
      if (Thread.interrupted()) throw new InterruptedException
      total += i
    }
    total
  }