1.三个线程,名称分别为”张三“,”李四“,”票贩子“,共同抢100张火车票
2.每个线程抢到一张票后,都必须休眠500毫秒,用来模拟网络延时
3.限”票贩子“只能抢一张票
public class TicketOffice implements Runnable{
private int count=100;
private int no=0;
private boolean flag=false;
public void run()
{
while(true)
{
if(!sale())
{
break;
}
}
}
public synchronized boolean sale() {
if(count==0)
{
return false;
}
no++;
count--;
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"抢到第"+no+"张票,"+"剩余"+count+"张票!");
if(Thread.currentThread().getName()=="票贩子")
{
return false;
}
return true;
}
}
public class Test {
public static void main(String[] args)
{
TicketOffice office=new TicketOffice();
Thread t1=new Thread(office);
Thread t2=new Thread(office);
Thread t3=new Thread(office);
t1.setName("张三");
t2.setName("李四");
t3.setName("票贩子");
t1.start();
t2.start();
t3.start();
}
}