本帖最后由 庄星睿 于 2012-6-5 12:16 编辑
今天复习同步锁时又遇到一个状况:- class Ticket implements Runnable
- {
- private int tick=100;
- Object obj=new Object();
- public void run()
- {
- while (true)
- {
- synchronized (new Object()) //这里把obj换成new Object()
- {
- if (tick>0)
- {
- try{Thread.sleep(10);}catch (Exception e){}
- System.out.println(Thread.currentThread().getName()+"...."+"tick:.."+tick--);
- }
- }
- }
- }
- }
复制代码- class TicketDemo
- {
- public static void main(String[] args)
- {
- Ticket t=new Ticket();
- Thread t1=new Thread(t);
- Thread t2=new Thread(t);
- Thread t3=new Thread(t);
- Thread t4=new Thread(t);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 运行结果:
Thread-1....tick:..6
Thread-2....tick:..5
Thread-2....tick:..4
Thread-1....tick:..2
Thread-3....tick:..3
Thread-0....tick:..1
Thread-1....tick:..0
Thread-2....tick:..-2
Thread-3....tick:..-1
Object obj=new Object()
synchronized(obj)
运行结果:
Thread-2....tick:..6
Thread-2....tick:..5
Thread-2....tick:..4
Thread-2....tick:..3
Thread-2....tick:..2
Thread-2....tick:..1
运行结果就不会出现异常 -1,-2 ,我传obj 和new Object()不都是Object的对象吗,为什么结果却不一样呢? |
|