What Are Three Ways in Which a Thread Can Enter The Waiting State

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

In Core Java, a thread can enter the waiting state in three main ways:

  1. By invoking Object.wait() method:
    • A thread can voluntarily enter the waiting state by calling the wait() method on an object. This method is used for inter-thread communication and synchronization.
    java
    synchronized (sharedObject) {
    sharedObject.wait();
    }
  2. By invoking Thread.sleep(long milliseconds) method:
    • A thread can enter the waiting state by calling the sleep() method, which causes the thread to pause for a specified amount of time. During this time, the thread is not actively executing.
    java
    try {
    Thread.sleep(1000); // sleeps for 1 second
    } catch (InterruptedException e) {
    // Handle interruption exception
    }
  3. By blocking on I/O:
    • A thread can enter the waiting state when it is waiting for an input/output operation to complete, such as reading from a file or waiting for data from a network socket.
    java
    InputStream inputStream = new FileInputStream("file.txt");
    int data = inputStream.read(); // Thread may block waiting for data

These are three common ways in which a thread can enter the waiting state in Core Java. It’s important to note that a thread in the waiting state can be later awakened or interrupted to resume its execution.