Problem description
The InterruptedException occurs when you invoke the interrupt() method after invoking the sleep (), wait (), or join () method on a thread. You can also invoke the isInterrupted() method if appropriate to check the interrupt status and catch and handle the exception. Then, the thread does not need to wait. The thread is directly controlled by the code that catches the exception block.
Solution
The InterruptedException occurs when you invoke the interrupt() method after invoking the sleep (), wait (), or join () method on a thread. You can use the code to control the thread and execute subsequent tasks.
Sample code
public class PlayerMatcher {
private PlayerSource players;
public PlayerMatcher(PlayerSource players) {
this.players = players;
}
public void matchPlayers() throws InterruptedException {
try {
Player playerOne, playerTwo;
while (true) {
playerOne = playerTwo = null;
// Wait for two players to arrive and start a new game
playerOne = players.waitForPlayer(); // could throw IE
playerTwo = players.waitForPlayer(); // could throw IE
startNewGame(playerOne, playerTwo);
}
}
catch (InterruptedException e) {
// If we got one player and were interrupted, put that player back
if (playerOne != null)
players.addFirst(playerOne);
// Then propagate the exception
throw e;
}
}
}