你能帮我解决这个问题。多线程的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'方法。 –