Additional Blogs by Members
cancel
Showing results for 
Search instead for 
Did you mean: 
Former Member
0 Kudos

Definition

A sequence or flow of execution in a Java program is called Thread. Threads are also called light weight process as they share the same data and process address space.

Thread Priority

Every thread has a priority based on which it gets preference for execution. Threads can have [1..10] priority values including the following:

java.lang.Thread.MIN_PRIORITY = 1
java.lang.Thread.NORM_PRIORITY = 5
java.lang.Thread.MAX_PRIORITY = 10



Threads are scheduled by Java runtime using fixed priority scheduling algorithm. Threads with higher priority generally (but this is not guarenteed) executes before threads with lower priority. However JVM may decide to execute a lower priority thread before higher priority thread to prevent starvation. A thread may at any time can also decide to give up its right to execute by calling the yield method. Threads can only yield the CPU to other threads having the same priority but if a thread attempts to yield to a lower priority thread the request is ignored.

Types of Thread

Threads are of two kinds namely a user thread and a daemon thread.

User Threads - User threads are normal threads and are generally used to run our programm code.

Daemon Threads - daemon threads are also known as service provider threads. They are generally used to execute some system code. JVM terminates daemon threads if no user threads are running. Therefore daemon threads should not be used to perform our program logic.

Life Cycle of a Thread

A thread can be said to be in the following states:

NEW - A thread which is not yet started.
RUNNABLE - A thread which is executing in the JVM.
BLOCKED - A thread that is blocked for a monitor by another thread.
WAITING - A thread that is waiting for an unspecified amount of time for another thread(s) to finish an action.
TIMED_WAITING - A thread that is waiting for a specified amount of time for another thread to finish an action.
TERMINATED - An exited thread is in this state.

Implementation

A thread can be implemented in Java in the following ways:

Thread Class:

An example using the Thread class.



Runnable Interface:

An example using the Runnable interface.

2 Comments