1:從方法角度來看java
sleep是Thread的方法,而wait是Object方法。ui
wait的含義是調用該對象wait方法的線程掛起,直到其餘線程來調用該對象的notify來從新激活這個被掛起的線程spa
sleep的含義是強制調用該線程掛起,必須讓其到達睡眠時間,或者經過調用interreput來打斷其睡眠線程
2:從資源角度來看code
wait是會釋放同步鎖,而sleep不會釋放同步鎖,wait不會佔用資源,而sleep是佔着cpu資源入睡對象
3:從代碼角度來看ci
wait必須是寫在synchronized塊裏,而sleep不是。資源
private final Object lock; private boolean ready; public void await() throws InterruptedException { synchronized (lock) { while (!ready) { try { lock.wait(5000L); } finally { if (!ready) { checkDeadLock(); } } } } } //mina檢查死鎖的方法 private void checkDeadLock() { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); // Simple and quick check. for (StackTraceElement s: stackTrace) { if (AbstractPollingIoProcessor.class.getName().equals(s.getClassName())) { IllegalStateException e = new IllegalStateException( "t" ); e.getStackTrace(); throw new IllegalStateException( "DEAD LOCK: " + IoFuture.class.getSimpleName() + ".await() was invoked from an I/O processor thread. " + "Please use " + IoFutureListener.class.getSimpleName() + " or configure a proper thread model alternatively."); } } // And then more precisely. for (StackTraceElement s: stackTrace) { try { Class<?> cls = DefaultIoFuture.class.getClassLoader().loadClass(s.getClassName()); if (IoProcessor.class.isAssignableFrom(cls)) { throw new IllegalStateException( "DEAD LOCK: " + IoFuture.class.getSimpleName() + ".await() was invoked from an I/O processor thread. " + "Please use " + IoFutureListener.class.getSimpleName() + " or configure a proper thread model alternatively."); } } catch (Exception cnfe) { // Ignore } } }
try{ System.out.println("I'm going to bed"); Thread.sleep(1000);System.out.println("I wake up"); } catch(IntrruptedException e) {}