⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 purcharse.java

📁 多线程 课堂讲解代码 很经典的
💻 JAVA
字号:
// 声明手推车类
class Handcart {
 private static final int MAXCARNUMBER = 1; // 手推车数量
 private int  cartNum = MAXCARNUMBER;       // 空闲手推车数量

 synchronized public void returnCar() { // 顾客买完东西把推车还回去
   cartNum++;
   notify();
 }

 synchronized public void getCar() {   // 顾客在进去买东西时取一辆推车
   while (cartNum == 0) {
     try {
       wait();
     } catch (InterruptedException e) {}
   } // while结束
   cartNum --;
   notify();
 } // getCar方法结束
} // 类Handcart结束

// 声明顾客类
class Customer implements Runnable
{
  private static int nextID = 1000;  // 初始化ID值
  private Handcart handcart;
  private int id ;                   // 顾客编号
  public Customer(Handcart handcart) {
    this.handcart = handcart;
    this.id = ++nextID;
  }

  // 顾客购物模拟
  public void run(){
    System.out.println("第 " + id + " 号顾客进入等车购物");
    handcart.getCar();        // 顾客在进去买东西时取一辆推车
     try{
        System.out.println("第 " + id + " 号顾客正在购物");
        // 随机生成顾客购物时间毫秒数
        int elcipTime = ( int ) ( Math.random() * 6000 );
        Thread.sleep( elcipTime );  // 线程休眠,模拟顾客购物
     }catch ( InterruptedException e ){}
     System.out.println("第 " + id + " 号顾客把推车还回去");
     handcart.returnCar();          // 顾客购物后归还推车
   } // run() 方法结束
} // 类Customer结束

public class Purcharse implements Runnable{
  private boolean stop = false;

  public static void main(String[] args) {
    System.out.println("超市购物模拟开始");
    Purcharse base = new Purcharse();
    new Thread( base ).start();
    try{
      Thread.sleep(300);
    } catch(InterruptedException e){}
   base.stop = true;
  } // main()方法结束

  public void run() {
   Handcart cart = new Handcart();
   while (!stop) {
     // 模拟顾客到来随机间隔毫秒数
     int eclipTime = (int)(Math.random() * 300);
     try{
       Thread.sleep( eclipTime );
     } catch(InterruptedException e){}
     Customer cust = new Customer(cart);  //创建顾客线程
     new Thread(cust).start();            //启动顾客线程
   } // while结束
 } // run方法结束
} // 类Purcharse结束

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -