多线程卖票

9.有一车票代售点,有4个窗口代售火车票,假设一共有100张(编号1100)火车票要售出。设计一个多线程程序,模拟车票代售点的售票过程。要求如下:

1)、用4个其他线程分别模拟4个窗口的售票过程。

2)、要求打印出每次所卖出的车票的票号。(如 “第1窗口卖出第3张火车票” 

 

3)、每次卖出车票后都要休息一下。

package work;

 

public class Testone {

 

public static void main(String[] args) {

Sell s = new Sell();

Thread t1 = new Thread(s);

t1.setName("窗口1");

Thread t2 = new Thread(s);

t2.setName("窗口2");

Thread t3 = new Thread(s);

t3.setName("窗口3");

Thread t4 = new Thread(s);

t4.setName("窗口4");

t1.start();

t2.start();

t3.start();

t4.start();

}

 

}

 

 

class Sell implements Runnable{

int num = 100;

boolean flag = true;

public void run() {

while(flag == true) {

synchronized(this) {

if(num>0) {

try {

Thread.sleep(100);

}

catch(InterruptedException e) {

System.out.println(e);

}

System.out.println(Thread.currentThread().getName()+"sell tickets:"+(100-num+1));

num--;

}

else if(num == 0) {

if(flag) {

System.out.println("没有票了");

flag = false;

}

}

}

}

}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值