public class Text5 {
public static void main(String[] args) {
Ticket ticket = new Ticket();
for (int i = 0; i < 4; i++) {
DemoH demoH = new DemoH(ticket);
Thread t1 = new Thread(demoH);
t1.start();
}
}
}
class DemoH implements Runnable {
private Ticket ticket;
public DemoH(Ticket ticket) {
this.ticket = ticket;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
ticket.purchase();//购票
}
}
}
class Ticket {
private int ticketAllNum = 100;//总票数
private int ticketIndex = 1;//票号
public synchronized void purchase() {
if (ticketAllNum > 0) {
System.out.println(Thread.currentThread().getName() + "购买了" + ticketIndex + "号票");
ticketIndex++;
ticketAllNum--;
return;
}
System.out.println("尊敬的" + Thread.currentThread().getName() + "票卖完了");
}
}
通过多线程模拟购票系统,假设总票数有100张,共四个线程进行售票,保证线程安全
最新推荐文章于 2023-05-21 21:14:20 发布