18.3 THREAD STATES


18.3 THREAD STATES

Although some of the thread states have already been mentioned in our description of the program ThreadsBasic.java, here is a more complete list:

  • born

  • runnable

  • running

  • waiting

  • sleeping

  • blocked

  • dead

When the constructor of a Runnable type is first invoked,[6] a new thread is born. Unless the method start is inside the constructor, the new thread just stays in the memory as a new object, basically doing nothing. When start is invoked on the thread either inside a constructor or in main, or at any other place in a program, the status of the thread changes from born to runnable, meaning that the thread can now be assigned a processor by the scheduler.

Assignment of a processor to a thread in a runnable state changes the state to running.[7] If a running thread is able to run to completion, its state changes to dead. Otherwise, the fate of the thread depends on whether there are other threads waiting for their turn at the processor. If the thread has the highest priority of all the currently runnable threads, it continues to be executed, unless the threads are timesliced by the platform. When threads are timesliced, as previously mentioned, a running thread is allocated a fixed time interval on the processor-a quantum. Timeslicing of equal-priority threads results in the processor being assigned to them in a round-robin fashion. If the code that a thread is executing contains yield, that would also cause a running thread to stop executing and yield the processor to another thread.

A running thread can be put to sleep by the sleep method. If threads contain long loops, putting threads to sleep in each iteration is a good strategy to ensure that no threads will have to wait unduly long to get their turn at the processor. When a running thread goes to sleep, one of the waiting threads gets a turn at the processor. An alternative to using sleep in long loops is to use yield.

The processor cannot be wrested away from a thread during an I/O operation in the run method, that being the case even for timesliced system. So we say that a thread blocks on I/O.

[6]As mentioned earlier in this chapter, an object of type Thread is also an object of type Runnable since the class Thread implements the Runnable interface.

[7]In the official Java documentation, both the runnable and the running states are referred to as runnable. But it makes practical sense to make a distinction between the two.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net