全部产品

org_json_JSONException

更新时间:2017-06-07 13:26:11

问题分析:

通过调用interrupt()方法,线程在sleep, wait, join时,会抛出InterruptedException,可以在适当地方配合isInterrupted()方法检查中断状态,并对异常进行捕获并处理,这样线程不用继续等待,线程控制权直接会转给catch住异常块的代码。

解决方案:线程在sleep、wait、join时如果对线程调用interrupt方法,会抛出InterruptedException,对该类异常进行捕获,可以获得线程控制权,继续执行任务。

代码示例:

  1. public class PlayerMatcher {
  2. private PlayerSource players;
  3. public PlayerMatcher(PlayerSource players) {
  4. this.players = players;
  5. }
  6. public void matchPlayers() throws InterruptedException {
  7. try {
  8. Player playerOne, playerTwo;
  9. while (true) {
  10. playerOne = playerTwo = null;
  11. // Wait for two players to arrive and start a new game
  12. playerOne = players.waitForPlayer(); // could throw IE
  13. playerTwo = players.waitForPlayer(); // could throw IE
  14. startNewGame(playerOne, playerTwo);
  15. }
  16. }
  17. catch (InterruptedException e) {
  18. // If we got one player and were interrupted, put that player back
  19. if (playerOne != null)
  20. players.addFirst(playerOne);
  21. // Then propagate the exception
  22. throw e;
  23. }
  24. }
  25. }

参考文献:

  1. https://docs.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html
  2. http://www.ibm.com/developerworks/cn/java/j-jtp05236.html
  3. http://blog.csdn.net/derekjiang/article/details/4845757