黑马程序员技术交流社区
标题:
obj锁与this锁有什么区别
[打印本页]
作者:
zlpiano
时间:
2015-7-22 23:52
标题:
obj锁与this锁有什么区别
下面注释的地方换成obj锁有什么区别,好像都不影响,如果没有区别,那以后都不用obj(要新建对象),直接用this不省事吗
class Demo2
{
public static void main(String[] args)
{
Ticket t1=new Ticket();
Thread th1=new Thread(t1);
Thread th2=new Thread(t1);
Thread th3=new Thread(t1);
Thread th4=new Thread(t1);
th1.setName("窗口1");
th2.setName("窗口2");
th3.setName("窗口3");
th4.setName("窗口4");
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class Ticket implements Runnable
{
static int num=1;
public void run()
{
while(true)
{
synchronized(this)//这里如果换成obj对程序有没有影响
{
if(num<1000)
System.out.println(Thread.currentThread().getName()+"售出第"+(++num)+"张票");
}
}
}
}
复制代码
作者:
xclyijin
时间:
2015-7-23 11:22
只要保证锁是唯一的,用this或obj都行。
作者:
张红(新)
时间:
2015-7-23 13:09
同步代码块的锁是任意的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2