条件结束java线程

时间:2012-12-01 17:52:18

标签: java concurrency

这是我在书中找到的停车场的一个小小的实施。 我想知道如何结束一个java线程。 如果在经过一段时间后仍然没有免费停车场,我想停止它,在我的情况下睡觉(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);
}
}

2 个答案:

答案 0 :(得分:3)

可以在几个层面上提供建议:

  1. 使用Java中断机制:调用yourThread.interrupt(),当你输入InterruptedException时(或者你已经在睡觉时),你会在线程中获得sleep; < / p>

  2. 不要从外面阻止你的线程;在线程中使用条件;

  3. 这将是最佳选择:不要使用sleep的无限循环;而是安排重复任务,您可以在需要时取消。

答案 1 :(得分:2)

boolean waited = false;

while (totalParkedCars >= MAX_CAPACITY) {
    try {
        System.out.println("The parking lot is full " +
                vehicle + " has to wait.");

        if (!waited) {
            waited = true;
            wait(500);
        } else {
            return;
        }
    } catch (InterruptedException e) {
        // ...
    }
}

非常简单。