在Java中,wait
方法和sleep
方法是用于线程控制的两种不同机制,它们有着不同的用途和行为。
1. wait
方法
- 定义:
wait
是Object
类的方法,用于线程间的通信,通常与同步(synchronized
)块/方法一起使用。 - 作用:使当前线程进入等待状态,直到其他线程调用该对象的
notify
或notifyAll
方法。 - 释放锁:调用
wait
时,当前线程会释放持有的对象监视器(锁)。 - 中断:可以被中断,抛出
InterruptedException
。
示例:
public class WaitExample {
private static final Object lock = new Object();
private static boolean isReady = false;
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread1: Waiting...");
try {
while (!isReady) {
lock.wait();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread1: Notified!");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread2: Setting isReady to true and notifying...");
isReady = true;
lock.notifyAll();
}
});
thread1.start();
try {
Thread.sleep(1000); // Ensure thread1 starts waiting first
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
}
}
2. sleep
方法
- 定义:
sleep
是Thread
类的方法,用于让当前线程暂停执行一段时间。 - 作用:使当前线程休眠指定的时间(毫秒、纳秒),不参与任何处理器调度。
- 不释放锁:调用
sleep
时,当前线程不会释放持有的对象监视器(锁)。 - 中断:可以被中断,抛出
InterruptedException
。
示例:
public class SleepExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("Thread1: Sleeping for 2 seconds...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread1: Awake!");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread2: Running...");
try {
Thread.sleep(1000); // Just to ensure thread1 starts first
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Thread2: Still running...");
});
thread1.start();
thread2.start();
}
}
主要区别总结
-
方法所属类:
wait
:属于Object
类。sleep
:属于Thread
类。
-
用途:
wait
:用于线程间的通信,等待其他线程的通知。sleep
:用于让线程暂停执行一段时间。
-
锁的行为:
wait
:释放当前持有的对象监视器(锁)。sleep
:不释放当前持有的对象监视器(锁)。
-
使用场景:
wait
:通常与synchronized
块/方法一起使用。sleep
:可以在任何需要暂停线程的地方使用。
通过理上述对比,可以更有效地使用 wait
和 sleep
方法来控制线程的行为,协调线程间的通信。