本帖最后由 不会耍筷子 于 2012-11-17 09:57 编辑
class Ticket implements Runnable
{
private int num = 200;
public void run()
{
while(true)
{
synchronized(new Object())
{
if(num > 0)
{
try
{
Thread.sleep(20);
}
catch (InterruptedException e)
{
}
System.out.println(Thread.currentThread().getName()+"....sale...."+num--);
}
else
break;
}
}
}
}
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();
}
}
不单独new一个Object类,直接在synchronized()里面new Object类,运行效果和没加同步代码块的效果一样,求解。
|