查看本章节
查看作业目录
需求说明:
车站只剩 50 张从武汉到北京的车票,现有 3 个窗口售卖,用程序模拟售票的过程
实现思路:
- 创建SellTicket类实现 Runnable 接口,定义实例变量ticket赋值50,重写run方法
- 在run方法内,定义while 死循环。在循环体中,调用 Thread 类的静态方法
- Thread.currentThread().getName() 获取当前运行线程的名称 ,打印线程名称和ticket变量值,然后让 ticket 自减。当 ticket 小于等于 0 时,结束循环
- 在测试类的 main() 方法内,创建SellTicket类实例一个
- 使用 new Thread(Runnable target) 构造方法开辟 3 条线程,并将 Runnable 实例 sellTicket 传给形参target
- 依次调用 3 个 Thread 类对象的 start() 方法,启动线程
实现代码:
这里会出现线程安全问题,出现多个窗口同时出售一张票的情况。
使用Runnable解决:https://blog.csdn.net/weixin_44893902/article/details/108815711
while循环实现:
//SellTicket售票处类实现 Runnable 接口
public class SellTicket implements Runnable {
int ticket = 50;// 剩余票数
@Override
public void run() {
//while循环实现
while (true) {
if (ticket<1) {
break;
} else {
System.out.println(Thread.currentThread().getName()+"出售第"+ticket--+"张车票");
}
}
}
public static void main(String[] args) {
SellTicket sellTicket = new SellTicket();
Thread thread1 = new Thread(sellTicket);
thread1.setName("窗口1");
thread1.start();
Thread thread2 = new Thread(sellTicket);
thread2.setName("窗口2");
thread2.start();
Thread thread3 = new Thread(sellTicket);
thread3.setName("窗口3");
thread3.start();
}
}
for循环实现:
//for循环实现
for (; ticket > 0; ticket--) {
System.out.println(Thread.currentThread().getName()+"出售第"+ticket+"张车票");
if(ticket==0) {
break;
}
}