Java多线程模拟实现售票功能,主要涉及Java的并发编程和线程同步操作。以下是实现该功能的步骤:
步骤一:创建Ticket类及构造方法
public class Ticket {
private int num;
public Ticket(int num) {
this.num = num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
注释:该类表示售票的对象,其中num表示剩余票数。
步骤二:创建Thread子类TicketSeller
public class TicketSeller extends Thread {
private final Ticket ticket;
private int nums;
public TicketSeller(Ticket ticket, int nums, String name) {
super(name);
this.ticket = ticket;
this.nums = nums;
}
@Override
public void run() {
while (ticket.getNum() > 0) {
synchronized (ticket) {
if (ticket.getNum() - nums >= 0) {
ticket.setNum(ticket.getNum() - nums);
System.out.println(Thread.currentThread().getName() + " sale " + nums + " tickets, there are " + ticket.getNum() + " left." );
} else {
System.err.println(Thread.currentThread().getName() + " sale " + ticket.getNum() + " tickets, the ticket has sold out.");
break;
}
}
try {
// 模拟售票时间
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
注释:该类继承自Thread类,主要用于售票线程的实现。其中,ticket表示售票对象,nums表示每次售票的数量。在run()方法中,通过synchronized关键字来实现线程同步。
步骤三:创建TicketSellerTest类
public class TicketSellerTest {
public static void main(String[] args) {
Ticket ticket = new Ticket(100);//创建售票对象
TicketSeller seller1 = new TicketSeller(ticket, 1, "售票窗口1");
TicketSeller seller2 = new TicketSeller(ticket, 2, "售票窗口2");
seller1.start();
seller2.start();
}
}
注释:该类为测试类,主要用于执行售票功能的调用。其中,创建售票对象ticket,同时创建两个售票窗口seller1和seller2。创建并启动售票线程。
步骤四:测试结果
运行TicketSellerTest类,运行结果如下:
售票窗口1 sale 1 tickets, there are 99 left.
售票窗口2 sale 2 tickets, there are 97 left.
售票窗口1 sale 1 tickets, there are 96 left.
售票窗口2 sale 2 tickets, there are 94 left.
售票窗口1 sale 1 tickets, there are 93 left.
售票窗口2 sale 2 tickets, there are 91 left.
售票窗口1 sale 1 tickets, there are 90 left.
售票窗口2 sale 2 tickets, there are 88 left.
...
注释:售票窗口1和售票窗口2异步售票,两个窗口共同售出了售票对象ticket中的100张票。
示例说明
- 如果将TicketSeller类的run()方法中synchronized改为锁住当前类对象,则每次只有一个线程能卖到票,其余线程都无法访问,从而失败。这说明线程同步的作用。
- 如果将Ticket类的构造方法中num改为0,则TicketSeller类的run()方法中不会进入循环,从而不会售票。这说明必须保证售票对象中票数大于0,否则售票无法进行。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java多线程模拟实现售票功能 - Python技术站