一、多线程模拟火车窗口售票
需求:模拟火车票100张,售票窗口
分析:
1.售票窗口使用线程来模拟
2.开4个窗口同时卖100张票
3.4个窗口卖票的任务是一样的
代码演示:
// 创建实现类,实现Runnable金额口
public class MyRunnable implements Runnable{
int tickets = 100;
// 重写run方法
@Override
public void run () {
while (true){
if(tickets < 1){
break;
}
System.out.println(Thread.currentThread().getName() + ":正在售出第" + tickets + "张票");
tickets--;
}
}
}
public static void main (String[] args) {
// 创建任务对象
MyRunnable mr = new MyRunnable();
// 创建四个窗口
Thread t1 = new Thread(mr,"窗口1");
Thread t2 = new Thread(mr,"窗口2");