Multithreading 是否有任何执行人连接到经纪人?
我需要在给定的毫秒内尽可能多次执行相同的任务。因此,我使用scala.actors.threadpool.Executors编写了以下代码Multithreading 是否有任何执行人连接到经纪人?,multithreading,scala,Multithreading,Scala,我需要在给定的毫秒内尽可能多次执行相同的任务。因此,我使用scala.actors.threadpool.Executors编写了以下代码 import actors.threadpool.{TimeUnit, Future, Executors} import collection.mutable.ListBuffer object TaskRepeater { def repeat(task: Runnable, millisecs: Long): Int = { val e
import actors.threadpool.{TimeUnit, Future, Executors}
import collection.mutable.ListBuffer
object TaskRepeater {
def repeat(task: Runnable, millisecs: Long): Int = {
val exector = Executors.newCachedThreadPool
val remover = Executors.newCachedThreadPool
val queue = ListBuffer[Future]()
def removeDone() {
(queue filter (_.isDone)) foreach { f =>
queue.remove(queue indexOf f)
}
}
val lock = new EasyLock()
val maxQueueSize = scala.collection.parallel.availableProcessors
val queueAvaiable = lock.mkCondition(queue.size < maxQueueSize)
var cnt = 0
val start = System.nanoTime()
while(System.nanoTime() - start < millisecs * 1000000) {
lock {
queueAvaiable.waitUntilFulfiled()
cnt += 1
val r = exector.submit(task)
queue += r
remover.submit(runneble {
r.get()
lock {
removeDone()
queueAvaiable.signalIfFulfilled()
}
})
}
}
exector.shutdown()
remover.shutdown()
assert(exector.awaitTermination(1, TimeUnit.SECONDS))
cnt
}
def runneble(f: => Unit) = new Runnable {
def run() {
f
}
}
}
import actors.threadpool.locks.{Condition, ReentrantLock}
class EasyLock {
val lock = new ReentrantLock
def mkCondition(f: => Boolean): EasyCondition = {
new EasyCondition(lock.newCondition(), f)
}
def apply(f: => Unit) {
lock.lock()
try {
f
} finally {
lock.unlock()
}
}
}
class EasyCondition(c: Condition, condition: => Boolean) {
def waitUntilFulfiled(f: => Unit) {
while (!condition) {
c.await()
}
f
}
def signalAllIfFulfilled() {
if (condition) c.signalAll()
}
def signalIfFulfilled() {
if (condition) c.signal()
}
}
有这样的执行者吗?如果我理解正确,您可以像这样使用
FuturePool
:
val b = new Broker[T]
val futurePool = FuturePool.defaultPool // or some other pool
futurePool(task).onSuccess { b ! _ }
谢谢你,阿列克西,这就是我想要的。请原谅我不要投赞成票,因为我的声望太低了:)@yakamoto我相信你仍然可以接受答案(点击选票下面的复选标记)。
val b = new Broker[T]
val futurePool = FuturePool.defaultPool // or some other pool
futurePool(task).onSuccess { b ! _ }