设计一个多线程的程序----火车售票模拟器。假如火车站有100张火车票要售出,现在有5个售票点同时售票,用5个线程模拟模拟这5个售票机的售票情况;
代码:package homework;
public class Test0527 {
public static void main(String[] args) {
Mashion a1=new Mashion(100);
for(int i=0;i<5;i++) {
Thread a=new Thread(new Drawing(a1),"售票机"+((char)('A'+i)));
a.start();
}
}
}
class Mashion{
int tickey;
public Mashion (int tickey) {
super();
this.tickey=tickey;
}
}
class Drawing extends Thread{
//int num;
Mashion a;
public Drawing (Mashion a) {
super();
//this.num=num;
this.a=a;
}
public void run() {
draw();
}
void draw() {
while(a.tickey>0) {
synchronized(a) {
if(a.tickey==0) {
System.out.println("余票不足");
return;
}
try {
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
a.tickey--;
}
System.out.println(Thread.currentThread().getName()+"卖了编号为"+a.tickey+"的票");
}
}
}
代码截图:
运行截图:
注意:
运用多线程时,要用sychronized去让线程避免同时进行,导致数据错误。