当前位置:   article > 正文

【Java编程学习】案例8-4 模拟12306售票_本案例要求编写一个模拟12306售票的系统,要求如下:假设需要抢票十次才可以抢到一

本案例要求编写一个模拟12306售票的系统,要求如下:假设需要抢票十次才可以抢到一

本案例要求编写一个模拟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();
             }
         }                         
     }        
     }
     }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

运行结果:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/632096
推荐阅读
相关标签
  

闽ICP备14008679号