A thread, t1, that waits for an explicit period of time for another thread, t2, to finish is in the TIMED_WAITING state.
This scenario is shaped in the following snippet of code:
- Create a thread: t1.
- Start t1 via the start() method.
- In the run() method of t1, add a sleep time of two seconds (arbitrary time).
- While t1 is running, the main thread prints the t1 state—the state should be TIMED_WAITING since t1 is in a sleep() that will expire after two seconds.
The code snippet is as follows:
public class TimedWaitingThread {
public void timedWaitingThread() {
Thread t = new Thread(() -> {
Thread.sleep(2000);
});
t.start();
Thread.sleep(500);
System.out.println("TimedWaitingThread t: "
+ t.getState()); // TIMED_WAITING
}
}
TimedWaitingThread twt = new TimedWaitingThread();
twt.timedWaitingThread();