黑马程序员技术交流社区
标题:
求大神调试下这个程序
[打印本页]
作者:
sixth
时间:
2012-11-9 14:36
标题:
求大神调试下这个程序
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
public class Test {
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(1000) ;
} 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(1000) ;
} 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(1000) ;
} 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(1000);
} 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 ;
}
为什么每次运行的时候在买到二十张票的时候就会抛异常,求解?
作者:
黄小贝
时间:
2012-11-14 10:18
小Q截图-20121114101635.png
(29.4 KB, 下载次数: 30)
下载附件
2012-11-14 10:17 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2