Extract from the Java Programmer's Guide to SCJP Certification: Threads:
static void yield () This method causes the current thread to temporarily suspend its execution and thereby allow the execution of other threads. For the JVM, decide when and when this transition will occur.
static invalid sleep (long milliseconds) is thrown InterruptedException The current thread falls asleep for the specified time before it becomes usable again.
final void join () throws InterruptedException final void join (long millisec) throws InterruptedException A call to any of these two methods called in the thread will wait and return until either of them completes, or ends after the specified time, respectively.
void interrupt () The method interrupts the thread on which it is called. In waiting, waiting, or blocking states for a connection, the thread will receive an Exception interrupt.
The following is an example of transitions between stream states. The stream in (1) is a little sleeping in (2), and then performs some calculations in the loop in (3), after which the stream ends. The main () method controls the flow in a loop in (4), printing the state of the stream returned by the getState () method. The output shows that the thread goes through the RUNNABLE state when the run () method starts execution, and then goes into the TIMED_WAITING state for sleep. When waking up, it calculates the loop in the RUNNABLE state and enters the TERMINATED state when the run () method completes.
Example: thread conditions
public class ThreadStates { private static Thread t1 = new Thread("T1") { // (1) public void run() { try { sleep(2); // (2) for(int i = 10000; i > 0; i--); // (3) } catch (InterruptedException ie){ ie.printStackTrace(); } } }; public static void main(String[] args) { t1.start(); while(true) { // (4) Thread.State state = t1.getState(); System.out.println(state); if (state == Thread.State.TERMINATED) break; } } }
Possible exit from the program:
RUNNABLE TIMED_WAITING ... TIMED_WAITING RUNNABLE ... RUNNABLE TERMINATED
source share