文章目录
- 相同点
- 不同点
看源码:
package java.lang;
public class Thread implements Runnable {
public static native void sleep(long millis) throws InterruptedException;
}
package java.lang;
/**
* Class {@code Object} is the root of the class hierarchy.
* Every class has {@code Object} as a superclass. All objects,
* including arrays, implement the methods of this class.
*
* @author unascribed
* @see java.lang.Class
* @since JDK1.0
*/
public class Object {
public final native void wait(long timeout) throws InterruptedException;
}
相同点
sleep() 和 wait()都可以暂停线程的执行。让线程等待若干时间
两者都需要捕获异常:InterruptedException
不同点
- 所属类不同
- sleep()是Thread类的静态方法。
- wait()是Object类的方法。
- 锁释放不同
- sleep()是不释放锁的。可以释放CPU执行权(执行时间分片)
- wait()是会释放目标对象的锁
- 用法不同
- sleep()方法睡眠指定时间之后,线程会自动苏醒。并且该方法必须指定时间参数。
- wait()方法被调用后,可以通过notify()或notifyAll()来唤醒wait的线程。wait()方法可指定时间参数也可不指定。
- 使用位置不用
- sleep()方法可以在任意地方使用
- wait()方法只能在同步代码块或者同步方法中使用(notify()或notifyAll()方法也是)
- 用途不同
- sleep()常用于一定时间内暂停线程执行。
- wait()常用于线程间交互和通信。