| 
 
| package com.itheima; /*5、 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、
 售票窗口、售票中心。售票中心分配一定数量的票,由若干个售票窗口进行出售,
 利用你所学的线程知识来模拟此售票过程。
 */
 public class Test5 {
 public static void main(String[]args){
 Ticket tt=new Ticket();
 TicketSealCenter tc=new TicketSealCenter(tt);
 SealWindow w1=new SealWindow(tt);
 SealWindow w2=new SealWindow(tt);
 SealWindow w3=new SealWindow(tt);
 SealWindow w4=new SealWindow(tt);
 new Thread(tc).start();
 new Thread(w1).start();
 new Thread(w2).start();
 new Thread(w3).start();
 new Thread(w4).start();
 }
 }
 //创建票的类,每张给一个ID
 class Piao{
 int id;
 Piao(int id) {
 this.id = id;
 }
 public String toString() {
 return "piao: " + id;
 }
 }
 class Ticket{//创建售票信息
 int index=0;
 Piao[] arrp=new Piao[100];
 public synchronized void set(Piao p){//提供给票的方法,用锁解决线程安全问题
 while(index==arrp.length){
 try {
 this.wait();
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 this.notify();
 arrp[index]=p;
 index++;
 
 }
 public synchronized Piao get(){//对外提供取票的方法,解决线程同步问题
 while(index==0){
 try {
 this.wait();
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 System.out.println("票已售欣,请稍后在试。。。。");
 }
 this.notifyAll();
 index--;
 return arrp[index];
 }
 }
 class SealWindow implements Runnable{//售票窗口调用取票的方法
 Ticket tc=null;
 SealWindow(Ticket tc){
 this.tc=tc;
 }
 public void run() {
 for(int i=0;i<20;i++ ){
 Piao p=tc.get();
 System.out.println("窗口剩余票:"+p);
 try {
 Thread.sleep(10000);
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }
 }
 class TicketSealCenter implements Runnable{//售票中心发布一定数量的票
 Ticket tc=null;
 TicketSealCenter(Ticket tc){
 this.tc=tc;
 }
 public void run() {
 for(int i=0;i<100;i++){
 Piao p=new Piao(i);
 tc.set(p);
 System.out.println("售票中心已发布票:"+p);
 try {
 Thread.sleep(1000);
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 
 }
 }
 
 
 
 
 
 
 
 | 
 |