1:从方法角度来看
sleep是Thread的方法,而wait是Object方法。
wait的含义是调用该对象wait方法的线程挂起,直到其他线程来调用该对象的notify来重新激活这个被挂起的线程
sleep的含义是强制调用该线程挂起,必须让其到达睡眠时间,或者通过调用interreput来打断其睡眠
2:从资源角度来看
wait是会释放同步锁,而sleep不会释放同步锁,wait不会占用资源,而sleep是占着cpu资源入睡
3:从代码角度来看
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) {}