package com.itheima;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
public class Test8 {
/**
* 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。
* 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
*/
public static void main(String[] args) {
//创建一个线程,不间断的生产票
final TicketSealCenter center=TicketSealCenter.getInstance();
Executors.newScheduledThreadPool(1).execute(new Runnable(){
public void run() {
while(true)
{
center.NewTicket();
}
}
});
//创建三个窗口进行售票服务
for (int i = 1; i < 4; i++) {
SealWindow sealWindow=new SealWindow();
sealWindow.setWindowID(i);
sealWindow.start();
}
}
//票类,这里只设置了一个票号字段
static class Ticket
{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
//售票中心
static class TicketSealCenter
{
//票的张数
private int count=1;
//存放窗口中要出售的票
private List<Integer> list=new ArrayList<Integer>();
//生成票号
public synchronized int NewTicket()
{
list.add(count);
return this.count++;
}
//售票窗口,要获得的售票的票号
public synchronized Integer getTicket()
{
if(list.size()>0)
{
return list.remove(0);
}else
{
return 0;
}
}
//单例模式
private static TicketSealCenter sealCenter=new TicketSealCenter();
public static TicketSealCenter getInstance(){
return sealCenter;
}
}
//售票窗口类
static class SealWindow{
//售票窗口的窗口号
private int WindowID;
public int getWindowID() {
return WindowID;
}
public void setWindowID(int windowID) {
WindowID = windowID;
}
TicketSealCenter sealCenter=TicketSealCenter.getInstance();;
public void start()
{
//用一个线程模拟取票的过程,Executors创建的线程会存放到线程池中,执行效率比较高
Executors.newSingleThreadExecutor().execute(new Runnable(){
public void run() {
//不间断的取票
while(true)
{
//在售票中心获得要出售的编号
Integer TicketID=sealCenter.getTicket();
Ticket ticket=new Ticket();
ticket.setId(TicketID);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (TicketID==0) {
System.out.println("票已经卖完了!");
}else
{
System.out.println(SealWindow.this.getWindowID()+"窗口卖出一张票;售出票的编号是:"+TicketID);
System.out.println();
}
}
}
});
}
}
}
|
|