在scala

时间:2017-03-26 17:52:36

标签: scala recursion scala-collections

object future1 {
    def main(args: Array[String]): Unit = {
        def getexecute(i:Int){
            println("start thread "+i)
            Thread.sleep(1000L)
            println("end of thread "+i)
        }       
        var n=10
        println("heelo"+n)
        def execute_future(n:Int):Unit = Future{
            println("hello")
            if(n<1){
                println("heelo")
                1
            }           
            else{
                println("get into future")
                getexecute(n)
                execute_future(n-1)
            }
        }
    }
}

我在将来递归地尝试调用getexecution方法但是未能进入未来。可能返回类型是单位无法进入未来。如何递归执行将来的调用?

1 个答案:

答案 0 :(得分:3)

这是一个与原始代码最接近的递归实现的示例。

//使用Scala 2.12(2.11用Future.successful(())替换Future.unit

object future1 {
    import scala.concurrent._
    import scala.concurrent.duration._
    import ExecutionContext.Implicits._
    def main(args: Array[String]): Unit = {
        def getexecute(i:Int){
            println("start thread "+i)
            Thread.sleep(1000L)
            println("end of thread "+i)
        }       
        def execute_future(n:Int):Future[Int] = Future.unit flatMap { _ =>
            println("hello")
            if(n<1) {
                println("heelo")
                Future.successful(1)
            } else {
                println("get into future")
                getexecute(n)
                execute_future(n-1)
            }
        }

        Await.result(execute_future(10), 15.seconds)
    }
}

执行它看起来像这样:

scala> future1.main(Array())
hello
get into future
start thread 10
end of thread 10
hello
get into future
start thread 9
end of thread 9
hello
get into future
start thread 8
end of thread 8
hello
get into future
start thread 7
end of thread 7
hello
get into future
start thread 6
end of thread 6
hello
get into future
start thread 5
end of thread 5
hello
get into future
start thread 4
end of thread 4
hello
get into future
start thread 3
end of thread 3
hello
get into future
start thread 2
end of thread 2
hello
get into future
start thread 1
end of thread 1
hello
heelo