同步块和监视器对象 [英] Synchronized block and monitor objects

查看:95
本文介绍了同步块和监视器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以解释一下,如果以下代码中的同步代码将限制对线程的访问。如果是,它是如何区别的,如果我们使用this作为监视器对象而不是msg。

Hi can someone explain if the in the following code the synchronized code will restrict access to the threads. If yes how is it different from, if we have used "this" as a monitor object instead of "msg".

public void display(String msg)    
{    
    synchronized(msg)    
    {    
        for(int i=1;i<=20;i++)    
          {    
               System.out.println("Name= "+msg);    
          }  
    }   
}


推荐答案

只有当两个线程使用完全相同的 msg 对象调用此方法时,您编写的方法才会阻止。

The method you wrote will block only if two threads will invoke this method with the exact same msg object.

如果您同步在 this 上,只有一个线程能够在给定时间调用该方法。

If you synchronize on this then it only one thread will be able to invoke the method at a given time.

这篇关于同步块和监视器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆