wait sleep区别

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) {}
相关文章
相关标签/搜索