本帖最后由 靓仔 于 2014-2-20 08:11 编辑
class Ticket implements Runnable
{
private int ticket = 100;
Object obj=new Object();
public void run()
{
while(true)
{
synchronized(obj)
{
if(ticket>0)
{
try{Thread.sleep(100);}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"sale ticket"+ticket--);
}
}
}
}
}
class ThreadSafe
{
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();
}
} |