本帖最后由 cs8630323 于 2015-2-15 18:48 编辑
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- /**
- 6、 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。售票中心分配一定数量的票,
- 由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
- */
- public class Test6 {
- public static void main(String [] args){
- //使用线程池执行任务
- ExecutorService pool = Executors.newCachedThreadPool();
- pool.submit(new SealWindow("1号窗口"));
- pool.submit(new SealWindow("2号窗口"));
- pool.submit(new SealWindow("3号窗口"));
- pool.submit(new SealWindow("4号窗口"));
- pool.submit(new SealWindow("5号窗口"));
- }
- }
- //票信息类。从售票中心获得票的数量,提供访问票数和修改票数方法
- class Ticket{
- Ticket(int n){
- num = n;
- }
- private int num;
- public int get() { return num; }
- public void set(int n){ num = n; }
- }
- //售票中心类
- class TicketSealCenter {
- private TicketSealCenter(){}
- private static Ticket tic;//票信息对象
- private int ticket = 100;//初始票数
- private static TicketSealCenter cen;//售票中心对象
- public synchronized void sellTicket(SealWindow win){
- if(ticket > 0) {
- ticket--;//票销售了一张
- tic.set(ticket);//修改票信息
- System.out.println(win.getName()+"销售车票一张,还剩余"+tic.get());
- }
- else System.out.println("车票卖光了");
- }
-
- //售票中心只有一个,使用单例创建。
- public static TicketSealCenter center(){
- if(cen == null){
- synchronized(TicketSealCenter.class){
- if(cen == null)
- cen = new TicketSealCenter();
- tic = new Ticket(cen.ticket);//票信息对象随着中心的建立而产生
- }
- }
- return cen;
- }
- //返回票信息对象
- public static Ticket getTicket(){
- return tic;
- }
- }
- //售票窗口类
- class SealWindow implements Runnable{
- SealWindow(String name){
- this.name = name;//设置窗口名
- }
-
- private String name ;//窗口名
- TicketSealCenter center = TicketSealCenter.center();//创建中心对象
- Ticket tic = center.getTicket();//票信息对象
- //访问窗口名方法
- public String getName(){
- return name;
- }
-
- public void run(){
- while(tic.get() > 0){
- center.sellTicket(this);//销售车票
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- System.out.println(name +"已无车票,明天再来");
- }
- }
复制代码 |
|