有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    sum方法需要知道它应该停止计算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
      }