黑马程序员技术交流社区

标题: obj锁与this锁有什么区别 [打印本页]

作者: zlpiano    时间: 2015-7-22 23:52
标题: obj锁与this锁有什么区别
下面注释的地方换成obj锁有什么区别,好像都不影响,如果没有区别,那以后都不用obj(要新建对象),直接用this不省事吗


  1. class Demo2
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 Ticket t1=new Ticket();
  6.                
  7.                 Thread th1=new Thread(t1);
  8.                 Thread th2=new Thread(t1);
  9.                 Thread th3=new Thread(t1);
  10.                 Thread th4=new Thread(t1);
  11.                
  12.                 th1.setName("窗口1");
  13.                 th2.setName("窗口2");
  14.                 th3.setName("窗口3");
  15.                 th4.setName("窗口4");
  16.                
  17.                 th1.start();
  18.                 th2.start();
  19.                 th3.start();
  20.                 th4.start();
  21.         }
  22. }

  23. class Ticket implements Runnable
  24. {
  25.         static int num=1;
  26.        
  27.         public void run()
  28.         {
  29.                 while(true)
  30.                 {
  31.                         synchronized(this)//这里如果换成obj对程序有没有影响
  32.                         {
  33.                                 if(num<1000)
  34.                                         System.out.println(Thread.currentThread().getName()+"售出第"+(++num)+"张票");
  35.                         }
  36.                 }       
  37.         }
  38. }
复制代码



作者: xclyijin    时间: 2015-7-23 11:22
只要保证锁是唯一的,用this或obj都行。
作者: 张红(新)    时间: 2015-7-23 13:09
同步代码块的锁是任意的




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