在使用java线程的时候,经常会用到wait方法,如果在调用wait方法的时候被中断,jvm会捕获这个中断不断调用wait 指令
这时候即使你使用interrupt 发法来中断都是没有用的.
需要对wait方法做一些封装,捕获异常,然后停止执行它
public static void wait(Object obj) { boolean interrupted = true; while (interrupted) { interrupted = false; try { obj.wait(); } catch (InterruptedException e) { interrupted = true; } } } public static void wait(Object obj, int timeout) { boolean interrupted = true; long startTime = System.currentTimeMillis(); int sleepTimeout = timeout; while (interrupted) { interrupted = false; try { obj.wait(sleepTimeout); } catch (InterruptedException e) { interrupted = true; long now = System.currentTimeMillis(); sleepTimeout -= now - startTime; startTime = now; if (sleepTimeout < 0) { interrupted = false; } } } }