A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 柳小龙 中级黑马   /  2013-8-4 23:24  /  1644 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

通过下面的两种方式都能实现线程互斥,但是synchronized (this)和synchronized (Outputer.class)两种方式的话,对于第一种用this和第二种用Outputer.class加锁,有什么不同或者相同的地方?各位力士,帮忙分析解释一下,谢谢了!!!
  //互斥方式1
  public synchronized void output(String str){
      synchronized (this) {  //??
         int length = str.length();
         for(int i = 0; i < length; i++){
             System.out.print(str.charAt(i));
         }
         System.out.println();
      }
  }


  //互斥方式2
  public static synchronized void output(Stringstr){//需将内部类Outputer申明为static
      synchronized (Outputer.class) {  //??
         int length = str.length();
         for(int i = 0; i < length; i++){
             System.out.print(str.charAt(i));
         }
         System.out.println();
      }
  }
}

评分

参与人数 1技术分 +1 收起 理由
神之梦 + 1 很给力!

查看全部评分

2 个回复

倒序浏览
//互斥方式1
  public synchronized void output(String str){//这里的锁对象是当前对象this
      synchronized (this) {  //??而这里的锁对象也是当前对象this,那么这里也就使用了嵌套锁。
         int length = str.length();
         for(int i = 0; i < length; i++){
             System.out.print(str.charAt(i));
         }
         System.out.println();
      }
  }

  //互斥方式2
  //同样方式二也采用嵌套锁,不过这里的内外层锁均是本类的的Class对象
  public static synchronized void output(Stringstr){//需将内部类Outputer申明为static
      synchronized (Outputer.class) {  //??
         int length = str.length();
         for(int i = 0; i < length; i++){
             System.out.print(str.charAt(i));
         }
         System.out.println();
      }
  }
}
相同处:两种方式均采用了双层嵌套锁,且内层与外层为同一个锁,方式一均采用当前对象作为锁,
方式二均采用同一个类的Class对象作为锁。
但在这里我不明白为会么说Output是一个内部类?如果发全码能看的更好一些,我认为方式2中采用
的是最外层的类。如果楼主说方式2中的Outputer是一个内部类,那么方式2中的内外层锁就不是同
一个了。

回复 使用道具 举报
好的。。{:soso_e113:}我把源代码附加了,你帮我分析下,主要是他们的“区别”,那种方式那种更好些?(我QQ:872618070)谢谢啦!!!

ThreadLock .rar

832 Bytes, 阅读权限: 30, 下载次数: 0

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马