- class Ticket implements Runnable
- {
- private int tick=1000;
- Object obj=new Object();
- public void run()
- {
- while (true)
- {
- synchronized(obj)
- {
- if (tick>0)
- {
- System.out.println(Thread.currentThread().getName()+" 卖出:"+tick--);
- }
-
- }
- }
- }
- }
复制代码- class Ticket implements Runnable
- {
- private int tick=100;
-
- public void run()
- {
- while (true)
- {
- synchronized(this)
- {
- if (tick>0)
- {
- System.out.println(Thread.currentThread().getName()+" 卖出:"+tick--);
- }
-
- }
- }
- }
- }
复制代码 上面两段代码,同步代码块中的对象不同,两个都能实现同步,有什么区别吗?
|
|