java多线程模拟多个售票员从同一个票池售票
程序功能
这段代码模拟了多个售票员从一个有限的票池中售票的过程。主要功能如下:
票池共有50张票,多个售票员(线程)并发进行售票。
使用同步机制确保线程安全,避免多个售票员同时出售同一张票。
每个售票员不断检查票池是否有票,有票则售出一张,直到票池中的票售完为止。
代码
class TicketSeller implements Runnable {// 票池中的剩余票数private static int tickets = 50;// 模拟售票方法@Overridepublic void run() {while (true) {// 同步代码块,保证多个线程安全操作票池synchronized (TicketSeller.class) {if (tickets > 0) {// 模拟售票过程System.out.println(Thread.currentThread().getName() + " 正在售出第 " + tickets + " 张票");tickets--;// 模拟售票需要一些时间try {Thread.sleep(100); // 休眠 100 毫秒} catch (InterruptedException e) {e.printStackTrace();}} else {// 如果票卖完了,退出售票System.out.println(Thread.currentThread().getName() + ":票已售罄");break;}}}}public static void main(String[] args) {// 创建三个售票员线程Thread seller1 = new Thread(new TicketSeller(), "售票员1");Thread seller2 = new Thread(new TicketSeller(), "售票员2");Thread seller3 = new Thread(new TicketSeller(), "售票员3");// 启动售票员线程seller1.start();seller2.start();seller3.start();}
}