优雅地替代 thread.sleep
时间: 2023-06-28 12:05:59 浏览: 1285
在 Java 中,可以使用 wait() 和 notify() 方法来替代 thread.sleep()。wait() 方法会让当前线程进入等待状态,直到另一个线程调用 notify() 方法来唤醒它。这种方式可以避免线程空转浪费 CPU 资源,提高程序效率。
以下是一个简单的例子:
```java
public class WaitNotifyExample {
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(new WaitThread(lock));
Thread t2 = new Thread(new NotifyThread(lock));
t1.start();
t2.start();
}
}
class WaitThread implements Runnable {
private Object lock;
public WaitThread(Object lock) {
this.lock = lock;
}
public void run() {
synchronized (lock) {
try {
System.out.println("WaitThread is waiting...");
lock.wait();
System.out.println("WaitThread is awake!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class NotifyThread implements Runnable {
private Object lock;
public NotifyThread(Object lock) {
this.lock = lock;
}
public void run() {
synchronized (lock) {
try {
System.out.println("NotifyThread is sleeping...");
Thread.sleep(5000);
lock.notify();
System.out.println("NotifyThread sent notification!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在这个例子中,WaitThread 会在 lock 上等待,直到 NotifyThread 调用 lock.notify() 方法唤醒它。NotifyThread 在睡眠 5 秒后,调用 lock.notify() 方法发送通知。这样,WaitThread 就会被唤醒,继续执行。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)