简体   繁体   English

在条件下结束Java线程

[英]End java thread on condition

This is a tiny implementation of parking lots that I found in a book. 这是我在书中找到的停车场的一个很小的实现 I'm wondering how to end a java thread. 我想知道如何结束Java线程。 Would like to stop it if there is still no free parking lots after a certain time passed, in my case sleep(500). 如果经过一定时间后仍然没有免费停车场,我想停止它(在我的情况下为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();
}
} 

Vehicle class: 车辆类别:

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;
    }
}
 }

A class for testing: 测试类:

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);
}
}

Advice can be given on several levels: 可以在几个级别上提供建议:

  1. Use the Java interruption mechanism: call yourThread.interrupt() and within the thread you'll get an InterruptedException when you enter sleep (or while you are already sleeping); 使用Java中断机制:调用yourThread.interrupt()并在线程内进入sleep (或已经处于睡眠状态)时,会收到InterruptedException

  2. don't stop your thread from the outside; 不要从外面停止线程; use a condition inside the thread; 在线程内使用条件;

  3. and this would be the best option: don't use an endless loop with sleep ; 这将是最好的选择:不要在sleep使用无限循环; instead schedule a repeated task that you can cancel when you need to. 而是安排一个重复的任务 ,您可以在需要时取消该任务

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) {
        // ...
    }
}

Pretty simple. 很简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM