// 示例代码:使用 wait 和 sleep 的区别
class Example {
// 使用 wait 方法
public synchronized void methodWithWait() {
try {
System.out.println("Start waiting...");
wait(); // 线程进入等待状态,必须在同步方法或同步块中调用
System.out.println("End waiting...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 使用 sleep 方法
public void methodWithSleep() {
try {
System.out.println("Start sleeping...");
Thread.sleep(2000); // 线程暂停 2 秒钟,不需要在同步方法或同步块中调用
System.out.println("End sleeping...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 唤醒等待的线程
public synchronized void notifyWaitingThread() {
notify(); // 唤醒一个正在等待的线程
}
}
public class Main {
public static void main(String[] args) {
Example example = new Example();
// 创建并启动一个新线程,该线程将调用 methodWithWait
Thread thread1 = new Thread(() -> example.methodWithWait());
thread1.start();
// 创建并启动另一个新线程,该线程将调用 methodWithSleep
Thread thread2 = new Thread(() -> example.methodWithSleep());
thread2.start();
// 主线程休眠 1 秒后唤醒等待的线程
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
example.notifyWaitingThread();
}
}
wait() 方法:
wait() 是 Object 类的方法,必须在同步方法或同步块中调用。wait() 后,当前线程会释放对象锁,并进入等待状态,直到其他线程调用 notify() 或 notifyAll() 唤醒它。wait() 可以指定等待时间(如 wait(long timeout)),但通常不带参数的 wait() 更常见。sleep() 方法:
sleep() 是 Thread 类的静态方法,不需要在同步方法或同步块中调用。sleep(long millis) 后,当前线程会暂停执行指定的时间(以毫秒为单位),但不会释放任何锁。sleep() 不会与其他线程交互,只是让当前线程暂时停止执行。notify() 方法:
notify() 是 Object 类的方法,用于唤醒一个正在等待该对象锁的线程。通过以上示例代码和解释,可以清楚地看到 wait() 和 sleep() 的主要区别。
上一篇:java数据库连接
下一篇:java try catch用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站