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

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

Prime, Fibonacci and Factorial number with example in java

Prime number, Fibonacci series and Factorial number programs are most commonly asked questions in interview. Read this article to know what is and how to write programs for prime number, fibonacci series and factorial number. Prime Number: prime number is natural number greater than 1 that has no positive divisor other than 1 and itself. A natural number greater than 1 is not a prime number, is called Composite number . For example, 7 is a prime number. Because it can divide with 1 and 7 only. Where as 8 is composite number. Since it has the divisor 2 and 4 in addition to the 1 and 8. The below example represents the finding the passing number is prime number or not. If the passing number is prime number it will print true otherwise it will print false. package com . javatbrains . practice ; public class PrimeNumber { public boolean isPrimeNumber ( int number ) { if ( number <= 1 ) return false ; // There's only one ...

JVM, JRE and JDK in Java

JVM, JRE and JDK are the most basic common concepts to know in java. These are the basic features to understand how Java architecture works? JVM stands for Java Virtual Machine, which doesn't have any physical directories created in java installation. JRE stands for Java Runtime Environment, which creates the directory under Java installation path and also present in JDK. JDK stands for Java Development Kit, which creates the directory in Java installation path and also it has it's own JRE. Since we have already learn that Java is platform independent means if we have implemented any of the java class in one environment, it will be executed in any other environment and provides the same output. But, JVM, JRE and JDK all are platform dependent . So that, for windows, linux, unix, mac, solaris..etc has it's own JVM, JRE and JDK. One will be not compatible with other environments. While installing the Java, we might come to know a bit about JRE and JDK. But, JVM is the other...