在Scala中创建非阻塞方法的好方法是什么?我能想到的一种方法是创建一个线程/ actor,该方法只是向线程发送一条消息并返回.有没有更好的方法来创建非阻塞方法?
Wal*_*ang 13
使用scala.actors.Future:
import actors._
def asyncify[A, B](f: A => B): A => Future[B] = (a => Futures.future(f(a)))
// normally blocks when called
def sleepFor(seconds: Int) = {
Thread.sleep(seconds * 1000)
seconds
}
val asyncSleepFor = asyncify(sleepFor)
val future = asyncSleepFor(5) // now it does NOT block
println("waiting...") // prints "waiting..." rightaway
println("future returns %d".format(future())) // prints "future returns 5" after 5 seconds
Run Code Online (Sandbox Code Playgroud)
带有多个参数的函数的重载"asyncify"留作练习.
然而,一个警告是异常处理.被"异步"的函数必须通过捕获它们来处理所有异常.抛出函数的异常行为未定义.
| 归档时间: |
|
| 查看次数: |
1861 次 |
| 最近记录: |