sleep()和wait()
在Java中,sleep()
和wait()
都是用于线程的控制,但它们有不同的作用和用法。
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"。
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
异常。