我在学校给了这个例子来帮助我了解生产者/消费者,我无法理解它。我整天都花在这上面,而且没有到达任何地方。
有谁能告诉我为什么它不会运行?
由于
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
答案 0 :(得分:1)
这一行没有编译
capacity = spaces = n;
应该是
this.capacity = spaces = capacity;
因为没有n
我建议您在尝试运行之前编译程序。