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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/229090.html
標籤:其他
上一篇:[JT]攻防世界web專項qwq
下一篇:斯坦佛密碼學十三講:1.概論
