What Is Multithreading In Java

multithreading in java

What is a thread?

A thread is a flow of execution through the process code, with its own program counter that keeps track of which instruction to execute next, system registers which hold its current working variables, and a stack which contains the execution history.

A thread shares with its peer threads few information like code segment, data segment and open files. When one thread alters a code segment memory item, all other threads see that.

A thread is also called a lightweight process. Threads provide a way to improve application performance through parallelism. Threads represent a software approach to improving performance of operating system by reducing the overhead thread is equivalent to a classical process.

Each thread belongs to exactly one process and no thread can exist outside a process. Each thread represents a separate flow of control. Threads have been successfully used in implementing network servers and web server. They also provide a suitable foundation for parallel execution of applications on shared memory multiprocessors. The following figure shows the working of a single-threaded and a multithreaded process.

WHAT IS MULTITHREADING?

In computer architecture, multithreading is the ability of a central processing unit to provide multiple threads of execution concurrently, supported by the operating system. This approach differs from multiprocessing.

Multithreading is the ability of a PROGRAM or an operating system process to manage its use by more than one user at a time and to even manage multiple requests by the same user without having to have multiple copies of the programming running in the computer. Each user request for a program or system service (and here a user can also be another program) is kept track of as a thread with a separate identity. As programs work on behalf of the initial request for that thread and are interrupted by other requests, the status of work on behalf of that thread is kept track of until the work is completed

TYPES OF MULTITHREADING

What is Multithreading? | Types, Uses of Multithreading with Career Scope

Types of Thread

  • User-level thread: They are created and managed by users. They are used at the application level. There is no involvement of the OS. A good example is when we use threading in programming like in Java, C#, Python, etc., we use user threads.

There are some unique data incorporated in each thread that helps to identify them, such as:

  1. Program counter: A program counter is responsible for keeping track of instructions and to tell which instruction to execute next.
  2. Register: System registers are there to keep track of the current working variable of a thread.
  3. Stack: It contains the history of thread execution.
  • Kernel-level Thread: They are implemented and supported by the operating system. They generally take more time to execute than user threads, for example, Window Solaris.

What is Multithreading? | Types, Uses of Multithreading with Career Scope

Multithreading Models

These models are of three types

  • Many to many
  • Many to one
  • One to on

Many to many: Any number of user threads can interact with an equal or lesser number of kernel threads.

Many to many

Many to one: It maps many user-level threads to one Kernel-level thread.

Many to one

One to one: Relationship between the user-level thread and the kernel-level thread is one to one.


One to one

What is Multithreading? | Types, Uses of Multithreading with Career Scope

Uses of Multithreading

It is a way to introduce parallelism in the system or program. So, you can use it anywhere you see parallel paths (where two threads are not dependent on the result of one another) to make it fast and easy.

For example:

  • Processing of large data where it can be divided into parts and get it done using multiple threads.
  • Applications which involve mechanism like validate and save, produce and consume, read and validate are done in multiple threads. Few examples of such applications are online banking, recharges, etc.
  • It can be used to make games where different elements are running on different threads.
  • In Android, it is used to hit the APIs which are running in the background thread to save the application from stopping.
  • In web applications, it is used when you want your app to get asynchronous calls and perform asynchronously.

Advantages of Multithreading

Below are mentioned some of the advantages:

  • Economical: It is economical as they share the same processor resources. It takes lesser time to create threads.
  • Resource sharing: It allows the threads to share resources like data, memory, files, etc. Therefore, an application can have multiple threads within the same address space.
  • Responsiveness: It increases the responsiveness to the user as it allows the program to continue running even if a part of it is performing a lengthy operation or is blocked.
  • Scalability: It increases parallelism on multiple CPU machines. It enhances the performance of multi-processor machines.
  • It makes the usage of CPU resources better.

Why should we use Multithreading?

We should use this because of the following reasons:

  • To increase parallelism
  • To make most of the available CPU resources.
  • To improve application responsiveness and give better interaction with the user.

WHAT IS MULTI-THREADING IN JAVA?

Multithreading in Java Tutorial with Examples

What is Multithreading in Java?

MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don’t allocate separate memory area, hence they save memory. Also, context switching between threads takes less time.

Example of Multi thread:

package demotest; public class GuruThread1 implements Runnable{       public static void main(String[] args) {        Thread guruThread1 = new Thread("Guru1");        Thread guruThread2 = new Thread("Guru2");        guruThread1.start();        guruThread2.start();        System.out.println("Thread names are following:");        System.out.println(guruThread1.getName());        System.out.println(guruThread2.getName());    }    @Override    public void run() {    } }

Multithreading in Java Tutorial with Examples

Some of the commonly used methods for threads are:

MethodDescription
start()This method starts the execution of the thread and JVM calls the run() method on the thread.
Sleep(int milliseconds)This method makes the thread sleep hence the thread’s execution will pause for milliseconds provided and after that, again the thread starts executing. This help in synchronization of the threads.
getName()It returns the name of the thread.
setPriority(int newpriority)It changes the priority of the thread.
yield ()It causes current thread on halt and other threads to execute.

Example: In this example we are going to create a thread and explore built-in methods available for threads.

package demotest;public class thread_example1 implements Runnable {    @Override    public void run() {    }    public static void main(String[] args) {        Thread guruthread1 = new Thread();        guruthread1.start();        try {            guruthread1.sleep(1000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        guruthread1.setPriority(1);        int gurupriority = guruthread1.getPriority();        System.out.println(gurupriority);        System.out.println("Thread Running");  }} 

Explanation of the code:

  • Code Line 2: We are creating a class “thread_Example1” which is implementing the Runnable interface (it should be implemented by any class whose instances are intended to be executed by the thread.)
  • Code Line 4: It overrides run method of the runnable interface as it is mandatory to override that method
  • Code Line 6: Here we have defined the main method in which we will start the execution of the thread.
  • Code Line 7: Here we are creating a new thread name as “guruthread1” by instantiating a new class of thread.
  • Code Line 8: we will use “start” method of the thread using “guruthread1” instance. Here the thread will start executing.
  • Code Line 10: Here we are using the “sleep” method of the thread using “guruthread1” instance. Hence, the thread will sleep for 1000 milliseconds.
  • Code 9-14: Here we have put sleep method in try catch block as there is checked exception which occurs i.e. Interrupted exception.
  • Code Line 15: Here we are setting the priority of the thread to 1 from whichever priority it was
  • Code Line 16: Here we are getting the priority of the thread using getPriority()
  • Code Line 17: Here we are printing the value fetched from getPriority
  • Code Line 18: Here we are writing a text that thread is running.

When you execute the above code, you get the following output:

Multithreading in Java

Output:

5 is the Thread priority, and Thread Running is the text which is the output of our code.

Java Thread Synchronization

In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data and another thread which is reading data at the same time, might create inconsistency in the application.

When there is a need to access the shared resources by two or more threads, then synchronization approach is utilized.

Java has provided synchronized methods to implement synchronized behavior.

In this approach, once the thread reaches inside the synchronized block, then no other thread can call that method on the same object. All threads have to wait till that thread finishes the synchronized block and comes out of that.

In this way, the synchronization helps in a multithreaded application. One thread has to wait till other thread finishes its execution only then the other threads are allowed for execution.

It can be written in the following form:

Synchronized(object){          //Block of statements to be synchronized}
0Shares

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *