Search code examples
javajava-threads

How to create a single thread cooldown


I'm finding the way to make a Single thread cooldown but get stuck. In the class who manages the cooldown I created a:

private HashMap<UUID,Integer> players = new HashMap<>();

//UUID = Player UUID
//Integer = Time in cooldown (Seconds)

public void run(){
for(UUID player : players){
    //WHAT I NEED TO DO HERE?
    if(//Time == 0){
      players.remove(player);
      }
   }
}

Didn't use an IDE hopefully I didn't miss an error that eclipse would have picked up.

But how I can get the integer and save it with a second less?


Solution

  • TimeUnit is used for delaying a process, as it could be used as followed:

    TimeUnit.SECONDS.sleep(1);

    This will delay the current thread by one second.

    I won't suggest using it, because your situation sounds more like a thread is working in the background and you want to wait till it has finished! Therefore use the new feature isAlive, which could be used in a (while) loop.


    Edit

    If you do want to delay a thread from another thread over the instance, then I'd suggest using the sleep method.

    Example:

    myThread.sleep(1000);
    

    This will delay myThread by one second.


    Edit #2

    To change a value for a certain key of a HashMap, use the put and get method.

    Example:

    // Get the time of a player and subtract it by one
    Integer value = players.get(player) - 1;
    // Update the value
    players.put(player, value);
    
    // If the time runs out, than delete the player
    if (value == 0){
        players.remove(player);
    }