线程中的WAITING和TIMED_WAITING有什么区别?

1 个回答

  • 唐小妍
    你会等一个人三五年吗?
    `WAITING` 和 `TIMED_WAITING` 是 Java 线程状态中的两种等待状态,主要区别在于线程是否设置了超时时间。 #### **1. `WAITING` 状态** **定义** `WAITING` 表示线程在等待某个条件满足,没有设置超时时间,线程将无限期地等待,直到被显式唤醒。 **特点** - 线程处于无限期等待状态。 - 线程需要依赖其他线程显式地唤醒(例如调用 `notify` 或 `notifyAll` 方法)才能继续执行。 **进入 `WAITING` 状态的常见方式** - 调用 `Object.wait()` 方法(无超时参数)。 - 调用 `Thread.join()` 方法(无超时参数)。 - 调用 `LockSupport.park()` 方法。 **示例** ```java public class WaitingExample { public static void main(String[] args) throws InterruptedException { Object lock = new Object(); Thread waitingThread = new Thread(() -> { synchronized (lock) { try { System.out.println("Thread is waiting..."); lock.wait(); // 无限期等待 System.out.println("Thread is resumed"); } catch (InterruptedException e) { e.printStackTrace(); } } }); waitingThread.start(); Thread.sleep(1000); synchronized (lock) { System.out.println("Main thread notifies..."); lock.notify(); // 唤醒等待线程 } } } ``` **输出结果** ``` Thread is waiting... Main thread notifies... Thread is resumed ``` #### **2. `TIMED_WAITING` 状态** **定义** `TIMED_WAITING` 表示线程在等待某个条件满足,并且设置了超时时间。如果超时时间到了条件还未满足,线程会自动退出等待状态。 **特点** - 线程等待一段有限的时间。 - 如果在超时时间内没有被显式唤醒,线程会自动恢复。 **进入 `TIMED_WAITING` 状态的常见方式** - 调用 `Thread.sleep()` 方法。 - 调用 `Object.wait(long timeout)` 方法。 - 调用 `Thread.join(long timeout)` 方法。 - 调用 `LockSupport.parkNanos(long nanos)` 或 `LockSupport.parkUntil(long deadline)` 方法。 **示例** ```java public class TimedWaitingExample { public static void main(String[] args) throws InterruptedException { Object lock = new Object(); Thread timedWaitingThread = new Thread(() -> { synchronized (lock) { try { System.out.println("Thread is waiting with timeout..."); lock.wait(5000); // 等待 5 秒 System.out.println("Thread is resumed or timeout occurred"); } catch (InterruptedException e) { e.printStackTrace(); } } }); timedWaitingThread.start(); Thread.sleep(2000); synchronized (lock) { System.out.println("Main thread notifies..."); lock.notify(); // 提前唤醒线程 } } } ``` **输出结果** ``` Thread is waiting with timeout... Main thread notifies... Thread is resumed or timeout occurred ``` #### **3. 区别** | **属性** | **`WAITING`** | **`TIMED_WAITING`** | |-------------------|--------------------------------------|--------------------------------------| | **定义** | 无限期等待某个条件满足。 | 等待某个条件满足或超时时间到达。 | | **进入方式** | `Object.wait()`、`Thread.join()` | `Object.wait(timeout)`、`Thread.sleep()` 等 | | **退出方式** | 被显式唤醒(如调用 `notify`)。 | 被显式唤醒或超时后自动退出等待状态。 | | **等待时间** | 无限期等待,没有时间限制。 | 有时间限制,超时后自动恢复执行。 | #### **4. 使用场景** - **`WAITING`** 适用于需要无限期等待某个条件的场景,例如消费者线程等待生产者提供数据。 - **`TIMED_WAITING`** 适用于需要限制等待时间的场景,例如网络请求超时控制、任务重试逻辑。
    发布于 2024-11-25 21:16 •IP属地 湖南
    举报
    评论
    收藏