Java Reference
In-Depth Information
Table 6-3. Methods That Place a Thread in a Timed-Waiting State
Method
Description
sleep()
This method is in the Thread class.
wait (long millis)
wait(long millis, int nanos)
These methods are in the Object class.
join(long millis)
join(long millis, int nanos)
These methods are in the Thread class.
parkNanos (long nanos)
parkNanos (Object blocker, long nanos)
These methods are in the LockSupport class, which is in the
java.util.concurrent.locks package.
parkUntil (long deadline)
parkUntil (Object blocker, long nanos)
These methods are in the LockSupport class, which is in the
java.util.concurrent.locks package.
A thread that has completed its execution is said to be in the terminated state. A thread is terminated when it
exits its run() method or its stop() method is called. A terminated thread cannot transition to any other state. You
can use the isAlive() method of a thread after it has been started to know if it is alive or terminated.
You can use the getState() method of the Thread class to get the state of a thread at any time. This method
returns one of the constants of the Thread.State enum type. Listing 6-14 and Listing 6-15 demonstrate the transition
of a thread from one state to another. The output of Listing 6-15 shows some of the states the thread transitions to
during its life cycle.
Listing 6-14. A ThreadState Class
// ThreadState.java
package com.jdojo.threads;
public class ThreadState extends Thread {
private boolean keepRunning = true;
private boolean wait = false;
private Object syncObject = null;
public ThreadState(Object syncObject) {
this.syncObject = syncObject;
}
public void run() {
while (keepRunning) {
synchronized (syncObject) {
if (wait) {
try {
syncObject.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
 
Search WWH ::




Custom Search