本帖最后由 杨永峰 于 2012-5-21 23:47 编辑
上代码:(自然不够全面、健壮,请多提出改进意见)- // 每日一题————————简单模拟售票过程。
- public class SaleWindows {
-
- public static void main(String[] args){
-
- SaleCenter sc = new SaleCenter(200);
- SaleTicket st = new SaleTicket();
- sc.setNum(st);// 售票中心分配票数
- // 创建线程
- Thread t1 = new Thread(st,"一号窗口");
- Thread t2 = new Thread(st,"二号窗口");
- Thread t3 = new Thread(st,"三号窗口");
- Thread t4 = new Thread(st,"四号窗口");
- Thread t5 = new Thread(st,"五号窗口");
- Thread t6 = new Thread(st,"六号窗口");
- // 启动线程
- t1.start();
- t5.start();
- t4.start();
- t2.start();
- t6.start();
- t3.start();
-
-
- }
- }
- class SaleTicket implements Runnable{
- private int tickets;
-
- public void setTotalNum(int tickets){
- this.tickets = tickets;// 设置发售总票数
- }
- private synchronized void sale(){
- if(tickets > 0){
- System.out.println(Thread.currentThread().getName() + "售出第 "+ (tickets--)+"张票");
-
- try{
- Thread.sleep(tickets);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- }
-
- public void run(){
- while(tickets > 0){
- sale();
- }
- }
- }
-
- class SaleCenter{
- private int ticketsnum;
-
- SaleCenter(int ticketsnum){
- this.ticketsnum = ticketsnum;
- }
- public void setNum(SaleTicket st)
- {
- st.setTotalNum(ticketsnum); // 授权票数上限
- }
- }
复制代码 |