【问题标题】:I don't understand this producer/consumer example我不明白这个生产者/消费者的例子
【发布时间】:2016-04-09 16:29:27
【问题描述】:

我在学校得到了这个例子来帮助我了解生产者/消费者,但我无法理解它。我花了一整天的时间,却没有任何进展。

谁能告诉我为什么它不能运行?

谢谢

public class CarPark {
   public static void main(String[] args) {

      CarParkControl carpark = new CarParkControl(4);

      Thread arrivals = new Thread(new Arrivals(carpark));

      Thread departures = new Thread(new Departures(carpark));

      arrivals.start();
      departures.start();

   }//main
}//CarPark



class Arrivals implements Runnable {

   CarParkControl carpark;
   Arrivals(CarParkControl c) {carpark = c;}

   public void run() {
      try {
         while(true) {
            carpark.arrive();
            Time.delay(RandomGenerator.integer(0,520));
         }
      } catch (InterruptedException e){}
   }
}



class Departures implements Runnable {

   CarParkControl carpark;
   Departures(CarParkControl c) {carpark = c;}

   public void run() {
      try {
         while(true) {
            carpark.depart();
            Time.delay(RandomGenerator.integer(0,520));
         }
      } catch (InterruptedException e){}
   }
}



class CarParkControl {

   protected int spaces;
   protected int capacity;

   CarParkControl(int capacity)
   {capacity = spaces = n;}

   synchronized void arrive() throws InterruptedException {
      while (spaces==0) wait();
      --spaces;
      notify();
   }//arrive

   synchronized void depart() throws InterruptedException {
      while (spaces==capacity) wait();
      ++spaces;
      notify();
   }//depart

}//CarParkControl

【问题讨论】:

  • 请发布您遇到的任何错误。
  • 是什么让您认为它不会运行?这个程序不会在屏幕上打印任何东西,所以如果你得到一个空白屏幕,那是正常的。
  • CarParkControl 构造函数中的n 是什么?没有n

标签: java concurrency


【解决方案1】:

这一行无法编译

 capacity = spaces = n;

应该是

 this.capacity = spaces = capacity;

因为没有n

我建议你在尝试运行之前先编译程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多