你能幫我解決這個問題。多線程的Java如何讓線程等待一段時間
停車問題
「有N停車地段在一個停車場,只能有一輛車如果所有的停車場都被佔用,那麼汽車會等待一段時間,如果仍然沒有免費的停車場,它就會離開。「
它需要使用線程來解決(由will同步)。
這裏是我的代碼:
停車
class Parking implements Runnable {
private Thread thread;
private String threadName;
static int parkingLots;
static {
parkingLots = 5;
}
Parking(String threadName) {
this.threadName = threadName;
}
public void run() {
if (parkingLots > 0) {
long restTime = (long) (Math.random() * 2000);
try {
parkingLots--;
System.out.println("Car " + threadName + " stands in the parking lot");
Thread.sleep(restTime);
} catch (InterruptedException e) {
}
parkingLots++;
System.out.println("Car " + threadName + " has left parking, it stood there" + ((double)restTime/(double)1000) + " s");
} else
System.out.println("Car " + threadName + " has left parking");
}
public void start() {
if (thread == null) {
thread = new Thread(this, threadName);
thread.start();
}
}
}
主要
public class Main {
public static void main(String[] args) {
ArrayList<Parking> parking = new ArrayList<Parking>();
for (int i = 0; i < 15; i++) {
parking.add(new Parking(String.valueOf(i + 1)));
}
for (Parking i: parking) {
i.start();
}
}
}
我希望看到的(當有2個停車場和4輛汽車):
Car 1 stands in the parking lot
Car 2 stands in the parking lot
Car 3 is waiting
Car 4 is waiting
Car 3 has left parking
Car 2 has left parking, it stood there 1.08 s
Car 4 stands in the parking lot
Car 1 has left parking, it stood there 1.71 s
Car 4 has left parking, it stood there 0.83 s
但是我得到了(當有2個停車場和4輛車時):所有第一輛車(1和2)站在停車位,其他車輛(3和4)剛剛離開,因爲沒有免費停車場。即使有15輛車,他們仍然無法進入。
那麼我該如何讓汽車在離開前等一段時間呢?如果有免費的停車場,那麼他們會去的,否則他們會離開停車場。
任何幫助,將不勝感激!謝謝!
,這個代碼需要一些嚴重的重構是以正確的方式完成 –
不要在'Runnable'中放置'Thread'。它應該是相反的。把主要班級想象成一個協調員;它將管理'ParkingLot'和'Car'類型的線程和實例的細節,每個類型都有一個'Runnable#run'方法。 –