赞
踩
本案例要求编写一个模拟12306售票的系统,要求如下:假设需要抢票十次才可以抢到一张票,会员需要300毫秒抢一次,普通用户需要800毫秒抢一次。
代码如下
package lianxi;//模拟12306售票 import java.lang.*; public class Lianxi28 { public static void main(String[] args) { Ticket a=new Ticket(); new Thread(a,"普通用户").start(); new Thread(a,"会员").start(); } } class Ticket implements Runnable{ public int l=1;//目前该买第几张了,总共10张票 public int usernumber=0;//普通用户抢票次数 public int vipnumber=0;//会员抢票次数 Object lock=new Object();//定义锁 public void run() { while(true){ synchronized (lock) { if(l>10) {break;} if(Thread.currentThread().getName().equals("普通用户")) { usernumber++; try{ Thread.sleep(800);//800毫秒抢一次 } catch(InterruptedException e){ e.printStackTrace(); } if(usernumber==10) {//抢够10次可以抢到一张票 System.out.println(Thread.currentThread().getName()+"购买到了第"+l+"张票"); usernumber=1; l++; } if(l<=10) { System.out.println("普通用户本轮第"+usernumber+"次抢票");} try{ Thread.sleep(100); // 当前线程休眠0.1秒 } catch(InterruptedException e){ e.printStackTrace(); } } else { vipnumber++; try{ Thread.sleep(300);//300毫秒抢一次 } catch(InterruptedException e){ e.printStackTrace(); } if(vipnumber==10) {//抢够10次可以抢到一张票 System.out.println(Thread.currentThread().getName()+"购买到了第"+l+"张票"); vipnumber=1; l++; } if(l<=10) { System.out.println("会员本轮第"+vipnumber+"次抢票"); } try{ Thread.sleep(100); // 当前线程休眠0.1秒 } catch(InterruptedException e){ e.printStackTrace(); } } } } } }
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。