Skip to main content

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:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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());
      }

}

OutPut:
      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.
1
Thread[main,5,main]

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,
1
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.

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...