设有火车票100张,创建10个线程模拟10个售票点,每个售票点100毫秒售出一张票。打印售票过程,注意使用synchronized确保同一张票只能卖出一次Java代码实现
时间: 2023-06-04 09:03:31 浏览: 159
使用多线程技术,模拟通过四个窗口卖出1000张火车票的功能。
以下是Java代码实现:
public class TicketSeller implements Runnable {
private static int ticketCount = 100;
private static final Object lock = new Object();
private String name;
public TicketSeller(String name) {
this.name = name;
}
@Override
public void run() {
while (ticketCount > 0) {
synchronized (lock) {
if (ticketCount == 0) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketCount--;
System.out.println(name + " 售出了一张票,剩余 " + ticketCount + " 张票");
}
}
}
}
public class TestTicketSeller {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
Thread thread = new Thread(new TicketSeller("售票点" + i));
thread.start();
}
}
}
阅读全文