问题分析
通过调用interrupt()
方法,线程在sleep/wait/join时,会抛出InterruptedException,可以在适当地方配合isInterrupted()
方法检查中断状态,并对异常进行捕获并处理,这样线程不用继续等待,线程控制权直接会转给catch住异常块的代码。
解决方案
线程在sleep/wait/join时如果对线程调用interrupt方法,会抛出InterruptedException,对该类异常进行捕获,可以获得线程控制权,继续执行任务。
代码示例
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;
}
}
}
参考文献
文档内容是否对您有帮助?