Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我不理解这个生产者/消费者的例子_Java_Concurrency - Fatal编程技术网

Java 我不理解这个生产者/消费者的例子

Java 我不理解这个生产者/消费者的例子,java,concurrency,Java,Concurrency,学校给我举了这个例子来帮助我了解生产者/消费者,但我无法理解。我花了一整天的时间在这上面,没有任何进展 有人能告诉我为什么它跑不动吗 谢谢 public class CarPark { public static void main(String[] args) { CarParkControl carpark = new CarParkControl(4); Thread arrivals = new Thread(new Arrivals(carpark))

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

有人能告诉我为什么它跑不动吗

谢谢

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

这行代码无法编译

 capacity = spaces = n;
应该是

 this.capacity = spaces = capacity;
因为没有n


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

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