- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Java:多线程模拟多站点售票过程 整理:曹岐赟
/113473/70767
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 MapDestation, Ticket tickets = HashMapDestation, Ticket();
private MapDestation, Integer records;
private static ListBookingOffice offices = ArrayListBookingOffice();
private int ticketsSold = 0;
private final int id;
new
new
// now todays tickets for sell:
static {
tickets.put(Destation.BEIJING, new
Destation.BEIJING));
Ticket(5,
tickets.put(Destation.SHANGHAI, Destation.SHANGHAI));
tickets.put(Destation.TIANJING, Destation.TIANJING));
}
public BookingOffice(int id) { this.id = id; offices.add(this); resetRecords();
new new
Ticket(5, Ticket(5,
}
private void resetRecords() {
records = new HashMapDestation, 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 customers coming:
Destation d Random().nextInt(Destation
= Destation. values()[new
.values().length)];
print(this + i want a ticket for + d);
// simulate the officers checking:
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) { e.printStackTrace();
}
// simulate the transaction:
Ticket wanted = tickets.get(d);
synchronized (wanted) {
if (!wanted.soldout()) {
print(this + sold a ticket for + d); wanted.degress();
addRecords(d);
++ticketsSold;
print(this + + d + tickets still have
+ wanted.getCurrent());
out.);
}
}
} else
print(this + tickets for + d + have been sold
print(this + closed);
print(this + totally sold tickets: + ticketsSold + ,sell records:
+ records);
}
public synchronized int getValue() {
return ticketsSold;
}
public String toString() {
return Officce- + id + ;
}
static void print(String s) { System.o
您可能关注的文档
最近下载
- 2025年江苏工会工作者招聘考试(工会基础知识)历年参考题库含答案详解.docx VIP
- 最新工会考试知识题库含答案.docx VIP
- 2025工会招聘社会化工会工作者综合知识专业能力测试题库.docx VIP
- 在线网课学习课堂《学术交流英语(哈工 )》单元测试考核答案.docx VIP
- 2025年陕西工会工作者招聘考试(工会基础知识)历年参考题库含答案详解.docx VIP
- 冬季管道排水工程施工方案(DOC).docx VIP
- 2025年社会化工会工作者综合素质与工会知识题库.docx VIP
- 清洁能源-氢能-课件.ppt VIP
- 2025年工会工作者法律法规与基础知识题库.docx VIP
- 爱默生质量流量计简明使用手册(一).pdf VIP
原创力文档


文档评论(0)