Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java wait和sleep的区别

作者:战天独尊   发布日期:2026-03-30   浏览:27

// 示例代码:使用 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();
    }
}

解释说明:

  1. wait() 方法

    • wait()Object 类的方法,必须在同步方法或同步块中调用。
    • 调用 wait() 后,当前线程会释放对象锁,并进入等待状态,直到其他线程调用 notify()notifyAll() 唤醒它。
    • wait() 可以指定等待时间(如 wait(long timeout)),但通常不带参数的 wait() 更常见。
  2. sleep() 方法

    • sleep()Thread 类的静态方法,不需要在同步方法或同步块中调用。
    • 调用 sleep(long millis) 后,当前线程会暂停执行指定的时间(以毫秒为单位),但不会释放任何锁。
    • sleep() 不会与其他线程交互,只是让当前线程暂时停止执行。
  3. notify() 方法

    • notify()Object 类的方法,用于唤醒一个正在等待该对象锁的线程。
    • 必须在同步方法或同步块中调用。

通过以上示例代码和解释,可以清楚地看到 wait()sleep() 的主要区别。

上一篇:java数据库连接

下一篇:java try catch用法

大家都在看

java url decode

java判断是windows还是linux

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java list 查找

java 解压rar

java读取excel中的图片

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站