Threads in java with example

Read this article to know what is thread and what is the lifecycle of thread in java. Threads concept introduced in java to achieve multiprocessing. Thread represents a separate path of program execution. All threads are running on top of the Main thread in java. This main thread is called daemon thread.

Explanation: A thread represents a separate path of execution of a group of statements. In a Java program, if we write a group of statements, then these statements are executed by JVM one by one. This execution is called thread, because JVM uses a thread to execute these statements. This means in every Java program there is thread is running internally.

Let us see the below program to find the thread used by JVM to execute the statements:
package com.javatbrains.threads;

public class CurrentThread {

      public static void main(String[] args) {
        System.out.println("Let us find the current thread");
        Thread t = Thread.currentThread();
        System.out.println("Current Thread: "+t );
        System.out.println("Its name= "+t.getName());


      Let us find the current thread
      Current Thread: Thread[main,5,main]
      Its name= main

In the above program, currentThread () is a static method in Thread class. So, we called it as Thread.currentThread() . Then method gave an object t of Thread class, it displayed its contents as.

In the above line first main indicates the name of the thread running the current code.We get 5 which is a number representing the priority of the thread. Every thread will have a priority number associated with it. The next main indicates the thread group name to which this thread belongs. A thread group represents a group of threads as a single unit.

Thread Life Cycle

A thread has many states in its life cycle. While starting from the birth of a thread, till its death, a thread exists in different states which are collectively called "Thread Life Cycle".

 A thread will born when it is created using Thread class as,
Thread t =  new Thread();

Then the thread goes into runnable state when start() method is applied on it. yield() method may pass a thread briefly, but the thread will be still in runnable state only.

From runnable state, a thread may get into not runnable state, when sleep(), or wait() methods act on it. A thread may be occasionally blocked on some I/O device where it is expecting some I/O from the user. After coming out from not- runnable state, again the thread comes back to runnable state.

Finally, a thread is terminated from memory only when it comes out of run method.

A thread represents execution of statements. The way the statements are executed is of two types.
                                    1.           Single Tasking
                                    2.           Multi Tasking

Single Tasking

 A task means doing some calculation, processing,etc. Generally a task involves execution of a group of statements, for example executing a program.

In single tasking, only one task is given to the processor ar a time. This means we are wasting a lot of processor time and microprocessor has to sit idle without any job for a long time. This is the drawback in single tasking.

Multi Tasking

To use the processor time in an optimum way, we can give it several tasks at a time. This is called multi tasking. Multi tasking is of two types:
                     1.   Process-based multi tasking
                     2.   Thread-based multi tasking

Process-based multi tasking:

The above diagram represents the round robin method. There are 4 tasks are present. Processor time will divide by 4 means each task takes 1/4 milliseconds time. First task executes in 1/4 milliseconds time, then it will come to next task2. But, this task not executed in expecting time that till come to task3. Task 3 will get execute and it will save in temporary memory. Similarly it will spent the same time in task4. Then it comes into first task and start executing where it left that task earlier. This is called 'round robin' method.

The main advantage of multi tasking is to use the processor time in a better way. We are engaging most of the processor time and it is not sitting idle. In this way, we can complete several tasks at a time, and thus achieve good performance.

Thread-based multi tasking:
In Process-based multi tasking, several programs are executed at a time, by the microprocessor. Thread-based multi tasking, several parts of the same program is executed at a time, by the microprocessor.
In the above diagram, program has two parts. These parts may represents two separate block of code or two separate methods containing code. Each part may perform a separate task. The processor should execute the two parts simultaneously. So the processor uses 2 separate threads to execute these two parts.

Achieving multi tasking with threads has one advantage, i.e. Since the threads are light weight processes, They use minimum resources of the system.

Uses of Threads:

Threads can be used for multiple processes. Some of the uses of threads are,
              1.  Threads are mainly used in server-side programs to serve the needs of multiple clients on a network or Internet.
              2. Threads are also used to create games and animations. 
       Animations means moving the objects from one place to another. In many games, generally we have to perform more than one task simultaneously.


Popular posts from this blog

Multithreading in java with example

JNDI configuration for Tomcat 9 with Oracle

String interview questions and answers