首页 > 代码库 > 简单的多线程买票模拟程序
简单的多线程买票模拟程序
/*
需求:
写一个简单的多线程模拟买票的程序
四个买票窗口,一共有100张票
*/
class Tick implements Runnable{
private static int tick=100;
private String window;
public void windowName(String window){
synchronized(Tick.class){
try{
Thread.sleep(1);
}catch(Exception e){}
this.window=window;
}
}
public void show(Object obj){
System.out.println(obj);
}
public void run(){
while(tick>0){
synchronized(Tick.class){
try{
Thread.sleep(10);
}catch(Exception e){}
if(tick>0)
show(window+": "+tick--+" 号票");
else
show(window+": 票已卖完");
}
}
}
}
public class TicketDemo{
public static void main(String args[]){
Tick tick0=new Tick();
Tick tick1=new Tick();
Tick tick2=new Tick();
Tick tick3=new Tick();
Thread t0=new Thread(tick0);
Thread t1=new Thread(tick1);
Thread t2=new Thread(tick2);
Thread t3=new Thread(tick3);
tick0.windowName("窗口1");
tick1.windowName("窗口2");
tick2.windowName("窗口3");
tick3.windowName("窗口4");
t0.start();
t1.start();
t2.start();
t3.start();
}
}
简单的多线程买票模拟程序