黑马程序员技术交流社区

标题: 线程互斥问题 [打印本页]

作者: 柳小龙    时间: 2013-8-4 23:24
标题: 线程互斥问题
通过下面的两种方式都能实现线程互斥,但是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();
      }
  }
}


作者: 施大勇    时间: 2013-8-5 18:11
//互斥方式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中的内外层锁就不是同
一个了。


作者: 柳小龙    时间: 2013-8-5 18:38
好的。。{:soso_e113:}我把源代码附加了,你帮我分析下,主要是他们的“区别”,那种方式那种更好些?(我QQ:872618070)谢谢啦!!!

ThreadLock .rar

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






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2