测试scala future时发生java.lang.IllegalMonitorStateException
我有以下测试课程:测试scala future时发生java.lang.IllegalMonitorStateException,scala,Scala,我有以下测试课程: @RunWith(classOf[JUnitRunner]) class NodeScalaSuite extends FunSuite with ScalaFutures { 在其中,我添加了此测试以检查返回未来的方法: test("Any should return the first future") { val p = Promise[Int]() p completeWith Future.any(List(Future{wait(2000);
@RunWith(classOf[JUnitRunner])
class NodeScalaSuite extends FunSuite with ScalaFutures {
在其中,我添加了此测试以检查返回未来的方法:
test("Any should return the first future") {
val p = Promise[Int]()
p completeWith Future.any(List(Future{wait(2000); 1}, Future{wait(1); 2}))
whenReady(p.future) {x =>
assert(true)
}
}
(我将assert设置为true
只是为了简化调试。)
当我运行测试套件时,出现以下错误:
[info] The future returned an exception of type: java.lang.IllegalMonitorStateException.
这是什么原因造成的?根据
java.lang.Object的文档#等待它
如果当前线程不是对象监视器的所有者,则引发非法监视器状态异常
这意味着应在synchronized
块内调用wait
。类似于synchronized{wait(2000)}
的东西应该可以工作,但我认为您真正想要做的是使用Thread.sleep(2000)
wait
与notify
和notifyAll
结合使用,用于同步多线程对共享资源的访问。它释放对象的监视器,以便另一个线程可以执行相同的同步块