2 zhoujay0755 zhoujay0755 于 2014.11.07 22:30 提问

java多线程同步问题,小弟百撕不得其解,特来求助!

多线程共享同一资源,同一张票卖出了多张!同步方法,同步代码块都没用。
问题:编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
public class ThreadDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new SealWindow(),"1号售票窗口");
Thread t2 = new Thread(new SealWindow(),"2号售票窗口");
Thread t3 = new Thread(new SealWindow(),"3号售票窗口");
Thread t4 = new Thread(new SealWindow(),"4号售票窗口");
Thread t5 = new Thread(new SealWindow(),"5号售票窗口");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}

}

class Ticket {
private int id;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

}

class SealWindow implements Runnable {
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
sellTicket();
}

public synchronized void sellTicket() {
    TicketSealCenter tsc = TicketSealCenter.getInstance();
    List<Ticket> tickets = tsc.getTickets();
    while (!tickets.isEmpty()) {
        Iterator<Ticket> it = tickets.iterator();
        Ticket ticket = it.next();
        System.out.println(Thread.currentThread().getName() + "...."
                + "卖了一张票,id为" + "..." + ticket.getId());
        tickets.remove(ticket);
    }
}

}

// 只有一个售票中心,所以把它设置成单例
class TicketSealCenter {
private static List tickets = new ArrayList();
private int ticketNum = 100;

private TicketSealCenter() {
    // 给每张票设置一个唯一的ID号
    setIdToTicket(tickets);
}

private static TicketSealCenter tsc = new TicketSealCenter();

// 提供一个公有方法,获取售票中心对象
public static TicketSealCenter getInstance() {
    return tsc;
}

private void setIdToTicket(List<Ticket> tickets2) {
    for (int i = 1; i <= ticketNum; i++) {
        Ticket ticket = new Ticket();
        ticket.setId(i);
        tickets.add(ticket);
    }
}

public List<Ticket> getTickets() {
    return tickets;
}

}

Csdn user default icon
上传中...
上传图片
插入图片