问题描述
上这门课:
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.locks.reentrantlock
class TimerClass{
var timer: Timer = new Timer()
var queue:Seq[Int] = Seq[Int]()
val lock: reentrantlock = new reentrantlock()
def task():TimerTask = {
new TimerTask {
def run () = {
lock.lockInterruptibly()
try {
println(s"running task!")
println(queue)
queue = Seq[Int]()
}
finally {
lock.unlock()
}
}
}
}
def activate(): Unit = {
lock.lockInterruptibly()
try {
println("activated")
//reset timer and reschedule task
timer.cancel()
queue = queue :+ 1
timer = new Timer()
timer.schedule(task(),1000L)
} finally{
lock.unlock()
}
}
}
当在 FunSuite 中进行测试时:
test("timer test"){
val timeclass = new TimerClass()
timeclass.activate()
timeclass.activate()
timeclass.activate()
}
测试运行并打印了 3 次激活,每次调用激活函数时一行,但是测试在运行 TimerTask 之前退出。我希望测试等到计时器的线程完成运行。我错过了什么?我也尝试作为守护进程运行,但这并没有解决它。我认为期货可能会在这里工作,但我不知道如何去做。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)