Multithreading in Java Thread Creation Method Use Example

1 What is a Thread in Java

A thread is light weight process that can execute simultaneously. Multithreading in java allows multiple threads to run simultaneously.

  • A program can be divided into two or more parts that can run concurrently and each part of such program is known as thread.
  • In a simple word, thread is a lightweight sub-process.
  •  It is a smallest unit of processing.
  • When these threads execute concurrently for accomplishing a task is known multithreading.
  • In multithreading, each thread defines a separate path of execution. 
  • In multithreading, every thread has a priority between 1 to 10. Thread with highest priority get preference over lower priority thread for execution.
Java Process and Thread Diagram
Fig: Java Process and Thread Diagram

 In a java programming, Thread is a predefined class within a java.lang package.

Operating system (OS) can contain multiple process, in the above figure, there are three process  P1,P2 & P3, within OS and within P3 process there are three threads T1, T2& T3. There is context-switching between the threads.  

2 Difference between Process and Thread

Difference between Process and Thread
ProcessThread
A process has their own virtual address space.Threads are entities within a process it uses its virtual address space of process.
Two processes running on the same system at the same time do not uses address space.Two threads running within a process uses the same address space.
Every process has its own data segmentAll threads within the process uses the same data segment of process.
In multiprocessing, processes use inter process communication techniques to interact with other processes.In multithreading, threads do not uses inter process communication techniques because they not uses separate address spaces. They share the same address space therefore, they can communicate directly with other threads within process.
Processes have considerable overhead.Threads have almost no overhead;
Process is heavy weight.Threads are light weight process (LWP).
Process contains much information about system, resource.Threads carry less state information than process
When we create a child process from a parent process then it requires duplication of the resources of parent process.No duplication of resources is required when we create a child thread from main thread.

3 How to create a thread in Java

We can create a thread by two ways:

  1. By extending Thread
  2. By implementing Runnable interface
How to create a thread in Java
Fig: How to create a thread in Java

Lets see multithreading in java with example

A Creating Thread By Implementing Runnable Interface

  1. We can create a thread by creating a class that implements the Runnable interface.
  2. To implement Runnable, a class only need to implement a single method called run().
  3. Inside run () we will define the code that constitute the new thread.    
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.  

Below is the multithreading program in java with implementing runnable interface

Example: Print hello to illustrate multithreading example in java

Output

Creating more than one thread in java :- multithreading in java example

Output

Another Example of Thread is

Result

Description:

Passing “this” as a argument, “DemoThread” is the name of the thread.  

In this program, main thread fineshes last because the main thread sleeps for 1000 milliseconds (1 seconds) between iteration, but the child thread sleeps for only 500 milliseconds.

This cause the child thread terminates earlier than main thread.

B Creating Thread By extending Thread class in java

  1. To create a thread we will create a thread a class that extends Thread class.
  2. To extend Thread class, a class only needs to implement a single method called run (). This extending class must override the run() method
  3. Inside run () we will define the code that constitute the new thread.                                                                                 
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.

Simple Thread example in java

Example: Write a thread program in java by extending thread class.

Multithreading in Java example programs

Example: Write a program to show multithreading in java by extending thread class

Multithreading in java example using Thread class

Result

4 Thread Methods in Java

Commonly used methods of Thread class are as follows

Sr NoMethod and Description
1void run()
Work execute as a thread is defined in this method .
2void start()
Used to start a thred which Calls the run() method of the thread or child class.
3static void sleep(long miliseconds)
Suspend the thread for specified amount of time.
4static void sleep(long miliseconds,int nanos)
Suspend the thread for specified amount of time.
5void join()
This method is used to pause the ececution of current thread until it die. void join().
6 void join(long miliseconds)
Pause the execution of current thread for the pecified miliseconds.
7void join(long miliseconds,int nanos)
Pause the execution of current thread for the pecified miliseconds and nano seconds.
8 boolean isAlive()
To checks a thread is alive or not.
9 String getName()
Returns the name of the thread.
10 setName(String name)
Used to set the name of thread.
11 int getPriority()
Get the priority of the thread.
12 void setPriority(int priority)
Set the priority of thread.
13 static Thread currentThread()
Returns the reference of currently executing thread
14 long getId()
Returns the id of the thread.
15 static void yield()
Temporarily pause the currently executing thread and allow other threads to execute.
16 void suspend()
Used to suspend the thread.
17 void resume()
Used to resume the suspended thread.
18 void stop()
Used to stop the thread.
19 void interrupt()
Interrupts the thread.
20 boolead isInterrupted()
Check whether the thead is interrupted or not

Use of thread in java

  1. To Reduce the time of execution of a program
  2. To achieve parallel execution

Read More

Thread Life Cycle in Java

How many ways to create thread in java

There are two ways to create thread in java

  1. By Extending Thread class
  2. By Implementing runnable Interface.

Types of thread in java

  1. Daemon thread provide services to other threads
  2. User defined threads Created by User

How to perform two tasks by two threads ?

Real time example of multithreading in java

  1. When two or more I/O operations are not dependent of each other then we can perform them by different threads.
  2. When tow or more Database read/write operations are not dependent then we can perform using multithreads.
  3. Sending OTP on mobile and email id at same time.
  4. Adding post on social media (fb, twitter, pintrest etc) on one click using publisher software.
  5. Servers are multithreaded they create separate thread to handle each request.

Java multithreading programming exercises

  1. Create Two threads using Thread class.
  2. Create Two threads using runnable Interface.
  3. Implement Produces consumer problem in Java.