我正在构建一个方法,该方法采用 x 大小的方法序列并返回要完成的第一个方法的结果。
def invokeAny(work: Seq[() => Int]): Int = ???
如何通过使用线程来实现这一点?(不允许期货)
这是我能想到的最好的方法,但似乎并非在所有情况下都有效。
def invokeAny(work: Seq[() => Int]): Int = {
@volatile var result = 0 // set to return value of any work function
val main = Thread.currentThread()
val threads: Seq[Thread] = work.map(work => new Thread( new Runnable {
def run { result = work(); main.interrupt(); }}))
threads.foreach(_.start())
for(thread <- threads) {
try {
thread.join()
} catch {
// We've been interrupted: finish
case e: InterruptedException => return result
}
}
return result
}
不是最漂亮的答案,但似乎有效:
def invokeAny(work: Seq[() => Int]): Int = {
@volatile var result = 0 // set to return value of any work function
val main = Thread.currentThread()
var threads: Seq[Thread] = Seq()
//Interrupts all threads after one is interrupted
def interruptAll = {
main.interrupt()
for(thread <- threads) {
thread.interrupt()
}
}
threads = work.map(work => new Thread(
new Runnable {
def run {
result = try {
work() } catch {
case e:InterruptedException => return
}
interruptAll;
}
}))
threads.foreach(_.start())
for(thread <- threads) {
try {
thread.join()
} catch {
// We've been interrupted: finish
case e: InterruptedException => return result
}
}
return result
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句