wait sleep区别

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) {}


转载于:https://my.oschina.net/u/3802/blog/227348

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值