Thread in java

Thread in java is one of the most important topics. A thread is the subpart of process and we can run a process by multiple threads that are known as multithreading. In this post we will read the thread in javajava thread example, what are the user thread and daemon thread in java with thread program in java.

Here is the table content of the article will we will cover this topic.
1. What is the thread in java?
2. Properties of thread?

3. Creation of thread using thread class
i) Creation of thread by extending thread class in java
ii) Creation of thread by anonymous class
4. Creation of thread using Runnable interface
i) Creation of thread by implementing Runnable interface in java
ii) Creation of thread by anonymous class
iii) Creation of thread by anonymous class(Lambda expression)
5. Creating multiple threads in java

What is the thread in java?

thread is a part(subprocess) of a program that can execute independently. In java multiple threads can run concurrently within a program. A process can run by multiple threads, each thread can run independently and work concurrently. Each program has at least one thread that is called the main thread. The main thread starts from the beginning of the main method and ends when the main method is executed completely. Each thread is created after the main thread because JVM starts from the main thread. A program can have any number of threads and each thread has a priority number that helps the JVM to prioritization of the threads.

Let’s take a java thread example that is a real time example of multithreading in java. Suppose an example of a website that has a number of pages. Multiple clients can make a number of requests at the same time and the webserver returns different pages on each request. It means the webserver application may have multiple threads that are running the multiple requests of the client. The application has multiple processes and each process may have subprocess that handled by a particular thread.

Thread in java

Let’s discuss the thread program in java. How does thread work and how we can use it? There are two ways to create a thread in java? We can create by Thread class or Runnable interface. We can read the creation of thread in java. Every program has at least one thread that is automatically created by JVM. Let’s see the thread program in java.

public class ThreadExample implements Runnable  
{
	public static void main(String arg[])
	{
		System.out.println("Main method");
		System.out.println("The main thread is running :"+Thread.currentThread().getName());
		ThreadExample obj = new ThreadExample();
		Thread t1 = new Thread(obj);
		t1.start();
	}

	@Override
	public void run() 
	{
		System.out.println("Thread is running..."+Thread.currentThread().getName());
	}
}

Output: Main method
The main thread is running :main
Thread is running…Thread-0

In the above example, we are creating a thread by use of Runnable interface. We will discuss later, how to create a thread by Runnable interface. As of now, we will focus on this example.
When JVM enters the main method, it creates a thread automatically that is called the main thread. you must be noticed the main thread is automatically created by JVM. In the next line, we are creating a thread t1 and starting the execution of thread t1 by start() method.

Thread in java

Properties of thread

Each thread has some common properties that helps the JVM to executes them and use these properties to predict the thread.

1. Lightweight process: A thread is a lightweight process in a program. A program can have any number of sub-processes that are handled by threads. That’s why we call the thread is a lightweight process.

2. Sharing resource: Multiple threads can share resources like data and code. A thread can make a change in data that are used by another thread. Even this concept leads to the duplicity of data. We will discuss it later.

3.  At least one thread : Each programhas at least one thread. Whenever we create a program the JVM automatically create a thread. A program can contain any number of threads.

4. Thread priority:  Each thread has a priority that lies between 1 to 10. The JVM automatically assigns the priority to each thread but we can it by setPriorty() method. The default priority of a thread is 5.  The JVM executes the higher priority thread before the lower priority. If two thread has same priority the thread scheduler decides which thread run first.

5. Creation of thread: A thread can create in two ways either by Thread class or Runnable interface.
We can create a thread by extends the Thread class or by implements the Runnable interface. The Thread class provides some methods and constructors that can be used to perform operations. We can learn it in detail.

6. Types of the thread: In java, we can create type of thread: user threads or daemon threads. The user thread has a higher priority than the daemon thread. A daemon thread always work in background and JVM can ignore them before terminating the process. But for the user thread, the JVM could not terminate the execution before completion of user thread. Like memory management, system management, signal processing are managed by daemon threads.

7. Life cycle of thread: A thread goes in different states during the execution of program. It has 6 states those are:

1. New state
2. Runnable state
3. Running state(This state doesn’t exist)
4. Blocked state
5. Waiting state
6. Timed waiting
7. Terminated state 

8. Thread scheduler: Execution of thread totally depends on the thread scheduler. A thread scheduler decides which thread should be run first. The thread scheduler depends upon the JVM. The JVM can indicate the thread scheduler those threads are more important or critical.

9. Stack: Each thread store the local variables and method calls in its own stack. The size of this stack depends on the JVM and it can be controlled using -XX:ThreadStackSize JVM option.

How to create thread in java

Before move further we will see the creation of thread in java. There are two ways to create a thread. In both the ways we need to write the code in the run() method. We will discuss it in details.
1. Extending the thread class.
2. Implementing the Runnable interface.

1. Thread creation by extending thread class in java

It’s the first way to create a thread in the program. We can create a thread by use of Thread class. and it exists in java.lang package. To create a thread in a program we need to extends the Thread class and override the run() method in our class. Actually, the code of thread must be placed in the run() method. Thread class has some methods and constructors that are used to create and perform some operations on the thread. We will discuss later the details of the Thread class.

Rules to create a thread:
1. To create a thread by use of Thread class we must extend the Thread class in our class.
2. We must override its run() method of Thread class.

Steps to create:

  • Create a class that extends the java.lang.Thread class.
  • This class overrides the run() method of Thread class.
  • Create an object of our class and call start() method.

Explanation of Steps: As we already discussed we want a thread by use of Thread class.
So, we must create a class that extends the Thread class. Now our class can inherit features of Thread class that are used to create and operate the thread. The life cycle of thread begins with run() method. So, we must override the run() method of Thread class. To start the execution of thread we must call the start() method. The start method() is present in Thread class. The start() method is used to start the execution of a thread. The start() method invokes the run() method on the Thread object.

class ExampleOfThreadCreation extends Thread
{  
   public static void main(String args[])
   {  
       System.out.println("Thread id of Main thread is = "+ Thread.currentThread().getId());
       ExampleOfThreadCreation t1= new ExampleOfThreadCreation();
       t1.start();
   }  
   public void run()
   {
     System.out.println("Thread is running...");
      System.out.println("Thread id of new thread is = "+Thread.currentThread().getId());
   }
}  

Output: Thread id of Main thread is = 1
Thread is running…
Thread id of new thread is = 12

As you can see in the above example, we are extending the Thread class in our class. We have overridden the run method() of the Thread class. In the overridden run method() we are providing the body of the new thread.

As you know in each program at least one thread is always running. That is the main thread. In our program, we are printing the Id of thread. So it is printing different id for both threads(Main thread and another created by us). Here we are creating a thread t1 and start the execution by call the start() method of thread.

2. Thread creation by implements the runnable interface

We can create a thread by use of a runnable interface. The runnable interface has only one method. It is abstract run() method. So, we must give it implementation if we are implementing the runnable interface.

Rules to create a thread:
1. To create a new thread by use of a runnable interface we must implement the runnable interface in our class.
2. We must provide the body to run() method of the runnable interface.

Steps to create:

  • Create a class that implements the runnable interface.
  • Implement the run() method of runnable interface and provide the body of the method.
  • Create an object of our class.
  • Create an object Thread class by using a constructor that accepts the object of Runnable.
  • Now call the start() method by an object of Thread class

Explanation of Steps: As we already discussed we want to create a thread by use of runnable interface. So, we must create a class that implements the runnable interface. We have to provide the body of an unimplemented method that is run method(). After that, we need to create the object of our class that implementing the Runnable interface. Create an object of Thread class by use of constructor that accepts the reference of the Runnable interface. We have to pass the object of the class that will implement the Runnable interface to the constructor of Thread class.

The life cycle of thread begins with run() method. To start the execution of thread we must call the start() method. The start method() is present in the Thread class. So we have to call to start the method by use of Thread class object. Start() invokes the run() method on the Thread object.

class ExampleOfThreadCreation implements Runnable
 {  
    public static void main(String args[])
    {  
        System.out.println("Thread id of Main thread is = "+ 
                Thread.currentThread().getId());
        ExampleOfThreadCreation obj = new ExampleOfThreadCreation();
        Thread thread = new Thread(obj);
        thread.start();
     }  
     public void run()
    {
           System.out.println("Thread is running...");
           System.out.println("Thread id of new thread is="+Thread.currentThread().getId());
    }
}  

Output:Thread id of Main thread is = 1
Thread is running…
Thread id of new thread is = 12

As you can see in the above example, we are implementing the Runnable interface in our class. We implement the run method() of the Runnable interface. As you know in each program at least one thread is always running. That is the main thread. In our program, we are printing the Id of thread. So, it is printing different id for both threads(Main thread and another created by us).

Leave a Comment