Java中使用多线程模拟多站点售票过程
时间:2011-03-23 zhangjunhd
这是一个在并发状态下对共享资源的多线程访问。这些访问必须是互斥的进行,因为涉及到对资源的修改。假设现在销售火车票。目的地有3个,分别是北京,天津和上海。使用一个枚举类型表示。
Destation.java
package com.zj.tickets;
public enum Destation {
BEIJING, SHANGHAI, TIANJING
}
下面设计车票类,final int original表示车票基数;int current表示当前还有多少张票;Destation destation表示目的地,它必须从上面的枚举型中取出其一。
Ticket.java
package com.zj.tickets;
public class Ticket {
private final int original;
private int current;
private final Destation destation;
public Ticket(int nums, Destation where) {
current = original = nums;
destation = where;
}
public int degress() {
return --current;
}
public int original() {
return original;
}
public boolean soldout() {
return current <= 0;
}
public Destation getDestation() {
return destation;
}
public int getCurrent() {
return current;
}
}
下面设计售票厅类,Map<Destation, Ticket> tickets表示目前可销售的车票种类,它通过一个static块初始化。Map<Destation, Integer> records是当前售票厅的火车票销售情况。List<BookingOffice> offices表示当前可工作的所有售票厅,每个售票厅是一个线程。int ticketsSold表示当前售票厅售出的火车票总数。int id表示当前售票厅编号。
每个线程都会模拟客户买票、工作人员查询数据库和售票交易过程。
模拟的数据为,当前发往北京、上海和天津的火车票各5张;每个售票厅交易5次(无论交易成功或失败)后关闭。
Java中使用多线程模拟多站点售票过程(2)
时间:2011-03-23 zhangjunhd
BookingOffice.java
package com.zj.tickets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class BookingOffice implements Runnable {
private static Map<Destation, Ticket> tickets = new HashMap<Destation, Ticket>();
private Map<Destation, Integer> records;
private static List<BookingOffice> offices = new ArrayList<BookingOffice>();
private int ticketsSold = 0;
private final int id;
// now today''s tickets for sell:
static {
tickets.put(Destation.BEIJING, new Ticket(5, Destation.BEIJING));
tickets.put(Destation.SHANGHAI, new Ticket(5, Destation.SHANGHAI));
tickets.put(Destation.TIANJING, new Ticket(5, Destation.TIANJING));
}
public BookingOffice(int id) {
this.id = id;
offices.add(this);
resetRecords();
}
private void resetRecords() {
records = new HashMap<Destation, Integer>();
}
private void addRecords(Destation d) {
Integer freq = records.get(d);
records.put(d, freq == null ? 1 : freq + 1);
}
public void run() {
int transaction = 5;
while (transaction-- > 0) {
// simulate a customer''s coming:
|