特性 | wait() |
sleep() |
---|---|---|
所在类和定义 |
Object 类中的实例方法 |
Thread 类中的静态方法 |
释放锁 | 是,调用wait() 会释放当前持有的对象锁 |
否,调用sleep() 不会释放任何锁 |
使用场景 | 线程间通信,通常与notify() 或notifyAll() 配合使用 |
让线程暂停执行一段时间,通常用于模拟延迟或调度任务 |
唤醒机制 | 依赖其他线程调用notify() 或notifyAll()
|
自动唤醒,经过指定时间后继续执行 |
抛出的异常 |
InterruptedException ,IllegalMonitorStateException
|
InterruptedException |
必须在同步块中调用 | 是,必须在synchronized 块中调用 |
否,不需要在synchronized 块中调用 |
示例代码
wait()
示例代码:
public class WaitExample {
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("Thread 1 is waiting.");
lock.wait();
System.out.println("Thread 1 is resumed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
try {
Thread.sleep(2000);
System.out.println("Thread 2 is notifying.");
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}
sleep()
示例代码:
public class SleepExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
System.out.println("Thread is sleeping for 2 seconds.");
Thread.sleep(2000);
System.out.println("Thread is awake.");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
}
}