这是我在一本书中找到的停车场的一个小实现。我想知道如何结束一个java线程。如果经过一段时间后仍然没有免费停车场,我想停止它,在我的情况下是 sleep(500)。
import java.util.logging.Level;
import java.util.logging.Logger;
class ParkingLot {
// I assume that parking lot capacity is 4 lots
public static final int MAX_CAPACITY = 4;
private int totalParkedCars = 0;
public synchronized void park(String vehicle) {
// check if there is a free lot
while (totalParkedCars >= MAX_CAPACITY) {
try {
System.out.println("The parking lot is full " +
vehicle + " has to wait.");
// a time that vehicle will wait for a parking lot to free
wait(500);
// ! I wait and if no free lots want to stop thread !
} catch (InterruptedException e) {
Logger.getLogger(ParkingLot.class.getName()).log(Level.SEVERE,
"Sorry for inconvenience :(", e);
}
}
// precondition is true
System.out.println(vehicle + " has parked");
totalParkedCars++;
}
public synchronized void leave(String vehicle) {
totalParkedCars--;
System.out.println(vehicle + " has left, notify a waiting vehicle.");
notify();
}
}
车辆等级:
import java.util.logging.Level;
import java.util.logging.Logger;
class Vehicle extends Thread {
private ParkingLot parking;
private String name;
private volatile boolean running = true;
public Vehicle(String name, ParkingLot parking) {
this.name = name;
this.parking = parking;
start();
}
public void terminate() {
running = false;
}
public void run() {
while (running) {
System.out.println(this.name + " is ready to park.");
parking.park(this.name);
try {
// Vehicle waits at lot
sleep(1000); // TODO: random time to wait
} catch (InterruptedException e) {
// Will catch and log InterruptedException if happens
Logger.getLogger(Vehicle.class.getName()).log(Level.SEVERE, this.name, e);
running = false;
}
// Vehicle leaves parking lot
parking.leave(this.name);
running = false;
}
}
}
用于测试的类:
public class GSTest {
public static void main(String[] args) {
ParkingLot parkingLot = new ParkingLot();
new Vehicle("Vehicle_1", parkingLot);
new Vehicle("Vehicle_2", parkingLot);
new Vehicle("Vehicle_3", parkingLot);
new Vehicle("Vehicle_4", parkingLot);
new Vehicle("Vehicle_5", parkingLot);
new Vehicle("Vehicle_6", parkingLot);
}
}