有两种场景:
一、1000张票开10个窗口卖
public class SoldTicket implements Runnable{
private Integer ticketCount = 1000;
@Override
public void run() {
while (true) {
synchronized (this) {
if(ticketCount > 0) {
System.out.println("售票员" + Thread.currentThread().getName() + "正在卖第" + ticketCount + "张票");
ticketCount--;
} else {
System.out.println("票已经售完,售票员" + Thread.currentThread().getName() + "结束售票");
break;
}
}
}
}
public static void main(String[] args) {
SoldTicket soldTicketPerson = new SoldTicket();
System.out.println("售票开始");
for(int i = 0; i < 10; i++) {
new Thread(soldTicketPerson, i + "").start();
}
}
}
二、一个人不停的放票,另一个人不停的售票,始终保持只有一张票可售卖
public class Ticket {
protected ArrayDeque ticketResource = new ArrayDeque();
protected Integer ticketNum = 1;
protected synchronized void sell() {
try {
while (true) {
if(ticketResource.size() > 0) {
System.out.println(Thread.currentThread().getName() + " 取走第" + ticketResource.pop() + "张票");
notify();
} else {
System.out.println("等待放票");
wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected synchronized void put() {
try {
while (true) {
if(ticketResource.size() <= 0) {
ticketResource.push(ticketNum);
System.out.println(Thread.currentThread().getName() + " 放入第" + ticketNum + "张票");
ticketNum++;
notify();
} else {
System.out.println("等待取票");
wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Ticket ticket = new Ticket();
PutTicketThread putTicketThread = new PutTicketThread(ticket, "ya");
SellTicketThread sellTicketThread = new SellTicketThread(ticket, "yu");
putTicketThread.start();
sellTicketThread.start();
}
}
public class PutTicketThread extends Thread{
private Ticket ticket;
public PutTicketThread(Ticket ticket, String name) {
super(name);
this.ticket = ticket;
}
public void run() {
ticket.put();
}
}
public class SellTicketThread extends Thread{
private Ticket ticket;
public SellTicketThread(Ticket ticket, String name) {
super(name);
this.ticket = ticket;
}
public void run() {
ticket.sell();
}
}
复习面试题……