1

注意:我不是在寻找解决方法;我敢肯定,如果有必要,我可以找到其他方法。我只是觉得我错过了一些基本的或古怪的东西,我想知道我错过了什么。或者,如果有一种方法可以使用调试器来获取更多信息,那也很好。谢谢!

我在使用同步时遇到问题。我收到了僵局,但这似乎完全不可能。我在每个同步调用之前、每个调用内部以及退出之前都放置了打印语句,这样我就可以看到谁拥有哪些同步对象。我发现即使当前没有人持有该对象的锁,它也不会进入我的同步调用之一。是否有一些我遗漏的怪癖或非法嵌套操作?这是我正在做的事情的要点。

哦,是的,最奇怪的是,删除两个“busyFlagObject”同步使它工作正常......

线程 1:

public void DrawFunction()
{
    synchronized(drawObject)
    {
        ...
        // Hangs here though nobody has a lock on this object
        synchronized(animationObject)
        {

        }
    }
}

线程 2:

public void AnotherFunction()
{
    synchronized(busyFlagObject)
    {
        // Calls a function that also uses this same Synchronized call
        synchronized(busyFlagObject)
        {
            // Calls another function that uses another Synchronized call
            // Hangs here waiting for the draw function to complete which it SHOULD 
            // be able to do no problem.
            synchronized(drawObject)
            {

            }

            // Never gets to this one assuming the Log statements don't 
            // buffer and aren't flushed but still shouldn't be a problem anyway.
            synchronized(animationObject)
            {

            }
        }
    }
}
4

1 回答 1

2

在调试器下运行您的应用程序或使用 JDK 工具中的“jstack”。这将直接向您显示哪些线程等待锁以及哪些持有锁,因此我们不必猜测您的问题出在哪里:-)

也就是说,您提到您在布尔值上同步。请记住,该类仅具有两个实例,并且许多事情(尤其是装箱)会隐式地将您的布尔实例更改为“共享”值。你确定你的锁对象不是同一个实例吗?您可以考虑使用new Object()作为您的监控对象。

It's worth noting that this isn't the only place that this can happen and there's a good entry on this problem in Java Concurrency in Practice, specifically with string interning, that I'm failing to find a link to at the moment. Don't use a type that isn't under your control as something it wasn't intended to do :-)

于 2013-01-09T03:09:19.140 回答