sleep()和wait()

在Java中,sleep()wait()都是用于线程的控制,但它们有不同的作用和用法。

  1. sleep()

sleep()方法是线程类(Thread)的静态方法,用于让当前线程暂停执行一段时间。它的作用是让当前线程进入阻塞状态,不会释放锁,等待指定的时间后再继续执行。sleep()方法的语法如下:

public static void sleep(long millis) throws InterruptedException

其中,millis参数表示线程需要暂停的时间,单位是毫秒。sleep()方法会抛出InterruptedException异常,当线程在sleep()期间被中断时会抛出该异常。

下面是一个使用sleep()方法的示例代码:

public class SleepExample {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Start");
        Thread.sleep(2000); // 暂停2秒
        System.out.println("End");
    }
}

输出结果为:

Start
End

在上面的代码中,主线程暂停了2秒后才输出了"End"。

  1. wait()

wait()方法是Object类的方法,用于让当前线程进入等待状态,直到其他线程调用该对象的notify()notifyAll()方法唤醒它。wait()方法的语法如下:

public final void wait() throws InterruptedException
public final void wait(long timeout) throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException

其中,timeout参数表示线程需要等待的时间,单位是毫秒。如果在等待时间内没有其他线程调用notify()notifyAll()方法唤醒它,线程会自动唤醒。wait()方法也会抛出InterruptedException异常,当线程在等待期间被中断时会抛出该异常。

下面是一个使用wait()方法的示例代码:

public class WaitExample {
    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        synchronized (lock) {
            System.out.println("Start");
            lock.wait(2000); // 等待2秒
            System.out.println("End");
        }
    }
}

输出结果为:

Start
End

在上面的代码中,主线程获取了一个锁对象,并调用了该对象的wait()方法等待2秒后才输出了"End"。注意,wait()方法必须在synchronized块中调用,否则会抛出IllegalMonitorStateException异常。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐