黑马程序员技术交流社区
标题:
火车票售票中心分配一定数量的票,由若干个售票窗口进...
[打印本页]
作者:
tfy
时间:
2012-12-2 12:42
标题:
火车票售票中心分配一定数量的票,由若干个售票窗口进...
package com.itheima;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
/** * 第七题 7、编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。
* 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程
* @author Administrator
*
*/
public class Test7 {
public static void main(String[] args) {
//售票中心不断产生新票
Executors.newSingleThreadExecutor().execute(new Runnable(){
public void run(){
TicketSealCenter stc = TicketSealCenter.getInctance() ;
while(true){
stc.newTicket() ;
}
}
}) ;
//售票窗口 1 开始售票
Executors.newSingleThreadExecutor().execute(new Runnable(){
SealWindow s1 = new SealWindow() ;
public void run(){
s1.setType(1) ;
while(true){
s1.seal() ;
try {
Thread.sleep(10000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}) ;
//售票窗口 2 开始售票
Executors.newSingleThreadExecutor().execute(new Runnable(){
SealWindow s2 = new SealWindow() ;
public void run(){
s2.setType(2) ;
while(true){
s2.seal() ;
try {
Thread.sleep(10000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}) ;
//售票窗口 3 开始售票
Executors.newSingleThreadExecutor().execute(new Runnable(){
SealWindow s3 = new SealWindow() ;
public void run(){
s3.setType(3) ;
while(true){
s3.seal() ;
try {
Thread.sleep(10000) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}) ;
}
}
/*票类
* */
class Ticket{
private int id ;
private double price ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
/*
* 售票窗口
* */
class SealWindow{
public TicketSealCenter tsc = TicketSealCenter.getInctance() ;
private Ticket ticket = null ;
private int type ; //售票窗口
//售票
public void seal(){
ticket = new Ticket();
int id = tsc.getTicket();
if (id == 0) {
System.out.println("第" + SealWindow.this.type + "号窗口暂时没票了,请稍等1秒钟..");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ;
}
ticket.setId(id);
ticket.setPrice(TicketPrice.PRICE);
System.out.println("第" + SealWindow.this.type + "号窗口卖出编号为:"
+ ticket.getId() + "的票");
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
/*售票中心
* */
class TicketSealCenter{
private List<Integer> list = new ArrayList<Integer>() ;
private int lastTicket = 0; //保存最后一张票
//产生新票
public synchronized Integer newTicket(){
list.add(++lastTicket) ;
return lastTicket ;
}
//取票
public synchronized Integer getTicket(){
if(list.size() > 0){
return list.remove(0) ;
}
return null ;
}
private TicketSealCenter(){ //单例设计
}
private static TicketSealCenter tics = new TicketSealCenter() ;
public static TicketSealCenter getInctance(){
return tics ;
}
}
/*票价类
* */
class TicketPrice{
public static double PRICE = 50 ;
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2