需求:编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,由若干个售票窗口进行出售。
运行的时候有重复的票号,我已经在卖票的方法上添加了synchronized关键字,还是会出现问题,但是我找不到问题出在哪里了,谢谢大家了
public class TicketDemo {
public static void main(String[] args) {
new Thread(new SealWindow("1号窗口")).start();
new Thread(new SealWindow("2号窗口")).start();
new Thread(new SealWindow("3号窗口")).start();
new Thread(new SealWindow("4号窗口")).start();
}
}
//票信息
class Ticket {
private static int ticketid;
public static int getTicketid() {
return ticketid;
}
public static void setTicketid(int ticket) {
ticketid = ticket;
}
}
//售票窗口
class SealWindow implements Runnable {
private String ticketname;
TicketSealCenter tsc = null;;
public SealWindow(String ticketname){
this.ticketname = ticketname;
tsc = TicketSealCenter.getInstance();
}
public void sellTicket(){
while(!tsc.hasTicket()){
System.out.println(ticketname+"卖出了第" + tsc.getid()+"号票!");
if (tsc.hasTicket()) {
System.out.println(ticketname+"的票已卖完!!");
}
}
}
public void run() {
sellTicket();
}
}
//售票中心
class TicketSealCenter {
private static TicketSealCenter tsc = new TicketSealCenter();
private static Ticket ticket = new Ticket();
private static int sumticket = 100;
private static boolean flag = false;
private TicketSealCenter(){}
public static TicketSealCenter getInstance(){
return tsc;
}
//询问是否有票,设置票面ID,并返回该ID
public static synchronized boolean hasTicket(){
if(sumticket > 0){
ticket.setTicketid(sumticket);
sumticket--;
}else {
flag =true;
}
return flag;
}
public int getid(){
return ticket.getTicketid();
}
}
------解决思路----------------------
public class TicketDemo {
public static void main(String[] args) {
SealWindow myWindow=new SealWindow();
new Thread(myWindow,"1号窗口").start();
new Thread(myWindow,"2号窗口").start();
new Thread(myWindow,"3号窗口").start();
new Thread(myWindow,"4号窗口").start();
}
}
//票信息
class Ticket {
private static int ticketid;
public static int getTicketid() {
return ticketid;
}
public static void setTicketid(int ticket) {
ticketid = ticket;
}
}
//售票窗口
class SealWindow implements Runnable {
TicketSealCenter tsc = null;
public SealWindow(){
tsc = TicketSealCenter.getInstance();
}
public void sellTicket(){
while(!tsc.hasTicket()){
// System.out.println(Thread.currentThread().getName()+"卖出了第" + tsc.getid()+"号票!");
if (tsc.hasTicket()) {
System.out.println(Thread.currentThread().getName()+"的票已卖完!!");
}
}
}
public void run() {
sellTicket();
}
}
//售票中心
class TicketSealCenter {
private static TicketSealCenter tsc = new TicketSealCenter();
private static Ticket ticket = new Ticket();
private static int sumticket = 100;
private static boolean flag = false;
private TicketSealCenter(){}
public static TicketSealCenter getInstance(){
return tsc;
}
//询问是否有票,设置票面ID,并返回该ID