Thread lifecyle explained

What is Thread ?

All Java programs have at least one thread, known as the main thread, which is created by the JVM at the program’s start, when the main() method is invoked with the main thread.

In Java, creating a thread is accomplished by implementing an interface and extending a class.

Every Java thread is created and controlled by the java.lang.Thread class.

LifeCycle of a Thread

Creating a Thread

A thread can be created by two ways :

By extending the thread class
By implementing the runnable interface

More about threads:

  • 1. Thread Name : To get the name of the thread use getName().
  • 2. getThreadGroup()-Returns the thread group to which this thread belongs. This method returns null if this thread has died (been stopped).
  • 3. Stack size : Local variables and refernce variables are stored in stack. The default stack size is 320k for 32bit and 1024k for 64bit.(Java SE 6).

Note: The minimum stack size should be 108k for 64bit(Java SE 8).

Starting a Thread: Start a thread by calling start() method on thread object. The thread has been created but it is not running, it is in waited state. At waiting state, other threads can interact with this thread.

Terminating a Thread: Once a thread has finished executing the run() method, the thread has to die. So, it gets terminated means the thread is dead.

A thread can be paused by using sleep(time) method . Can be suspended by using wait method .Sleep() method will make sure that the thread sleeps atleast for the amount of time we passed in the sleep method , but there is no such guarantee for the wait method .

Please comment below in case you have any doubts regarding threads or multi threading.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s