Skip to Content

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

image

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.

To report this post you need to login first.

2 Comments

You must be Logged on to comment or reply to a post.

  1. Bernd Eckenfels
    Note, there are so many problems with extending Thread (cant use other base classes, cant schedule Runnable from a Pool, Memory Leak for not-started Threads on older JVMs) I would not recommend to use it.

    Besides that, you should minimize the creation of threads and keep them alive for long. This is especially true for long running servers. Better write a scheduleable work item class and feed it to some kind of Workload manager. (For example XI has its own Thread Starter for Adapters)

    Greetings
    Bernd

    (0) 

Leave a Reply