【发布时间】: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