2

我希望能够访问从产生未来返回的对象

import scala.actors.Future
import scala.actors.Futures._

class Object1(i:Int) {
    def getAValue(): Int = {i}
}

object Test {
    def main( args: Array[String] ) = {
        var tests = List[Future[Object1]]()
        for(i <- 0 until 10) {
            val test = future {
                val obj1 = new Object1(i)
                println("Processing " + i + "...")
                Thread.sleep(1000)
                println("Processed " + i)
                obj1
            }
            tests = tests ::: List(test)
        }
        val timeout = 1000 * 60 * 5  // wait up to 5 minutes
        val futureTests = awaitAll(timeout,tests: _*)

        futureTests.foreach(test => println("result: " + future()))
    }
}

此代码的一次运行的输出是:

Processing 0...
Processing 1...
Processing 2...
Processing 3...
Processed 0
Processing 4...
Processed 1
Processing 5...
Processed 2
Processing 6...
Processed 3
Processing 7...
Processed 4
Processing 8...
Processed 6
Processing 9...
Processed 5
Processed 7
Processed 8
Processed 9
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>

我试过future().getClass(),输出是

result: class scala.actors.FutureActor

我希望能够访问的是 obj1 对象。

谢谢

布鲁斯

4

1 回答 1

2

你需要做这样的事情。的回报awaitAllList[Option[Any]]。这意味着每个未来的结果都是一个 Option[Any] 所以你需要一个匹配来获取值并将其转换为获取getAValue

    futureTests.foreach(test => test match {
        case Some(r) => println("result: " + r.asInstanceOf[Object1].getAValue)
    })

@James Iry 致敬

于 2011-01-10T20:29:39.330 回答