本帖最后由 董志超 于 2012-9-28 06:00 编辑
class Ticket implements Runnable
{
private int tick = 100;
//Object obj = new Object();
public void run()
{
while(true)
{
synchronized(new Object())//红色部分不注释,同步中传obj,无安全问题。红色部分注释后,同步中传new Object(),却出了安全问题。why?
{
if (tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"..sale.."+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();
}
}
|