看着 HTTP://download.eclipse .ORG /码头/稳定-7 /外部参照/ COM / ACME / ChatServlet.html 时,我似乎并不理解为什么需要有以同步的方法的同步块,像这样:

private synchronized void chat(HttpServletRequest request,HttpServletResponse response,String username,String message)
throws IOException
{
    Map<String,Member> room=_rooms.get(request.getPathInfo());
    if (room!=null)
    {
        // Post chat to all members
        for (Member m:room.values())
        {
            synchronized (m)
            {
                m._queue.add(username); // from
                m._queue.add(message);  // chat

                // wakeup member if polling
                if (m._continuation!=null)
                {
                    m._continuation.resume();
                    m._continuation=null;
                }
            }
        }
    }

为什么m需要被(再次?)同步如果整个方法已经是线程安全的?

感谢您任何的洞察力。

有帮助吗?

解决方案

在同步方法“聊天(...)”在其上的同步实例对象,而所述同步(M)同步“m”个对象上 - 因此它们被同步在两个不同的对象。基本上,它是确保一些其他的服务器对象不与同一成员实例在同一时间搞乱。

其他提示

当整个方法是同步在this对象上获得的锁。但上述同步块取得目前正在迭代中使用的部件上只有锁。

同步是在不同的锁。

在该方法定义中的关键字synchronized意味着,上this同步其它代码不能运行并行运行该方法。

synchronized(m)范围意味着,上m其他同步代码不能并行运行到环路。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top