Multithreading in JAVA

What is Multithreading?

Sukhpreet Singh
5 min readJan 5, 2022
Multithreading in JAVA (source : Google)

Want to learn how Multithreading actually works rather than just going through theory?

If yes, then you are at a right place. In this article we will learn about multithreading in java with its examples.

Don`t worry about any Prerequisites required for this post, we will cover each and everything from scratch. So before going into multithreading some of you will be wondering what is threading in programing domain. Let`s take a glance at threading in computing world.

THREADING

Thread in a Program(source : Google)

Threading is a process of creating thread in programs. Let`s understand this concept in the context of operating system. Every Pc has it`s own operating system which runs every single task with the help of processor. And we have only one processor in our Pc, so how does our operating system can perform multiple tasks at a same time. Its because the processor give its processing time equally to every process. It does not wait for any process to be completed in one go. It subsequently handles them one by one according to their priorities. So imagine that the processor has a thread (Hypothetically) which it uses to connect to these different processes to execute them. This is called threading ,making a connection with processor to run a process .The Definition of thread is that it is a light weight process which helps in running the tasks in parallel. . The threads work independently and provides the maximum utilization of the CPU, thus enhancing the CPU performance. So for this instance consider thread nothing but a specific function of a program designed to perform some task. A thread must have its own execution stack and program counter. The code running within the thread works only within that context. Each and every thread when created have their own life cycle. Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

Now if you got some idea of what threading is we will move to concept of multithreading. Here we will be discussing about what is multithreading, how to implement it with examples and some of its pros and cons.

Multithreading

A Web browser is the best example of a multithreaded application. Within a typical browser, you can scroll a page while it’s downloading an applet or an image, play animation and sound concurrently, print a page in the background while you download a new page, or watch three sorting algorithms race to the finish. Isn`t it amazing! how everything works parallelly.

Multithreading in java (Source : Google)

Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multi-threaded applications execute two or more threads concurrently. Hence, it is also known as Concurrency in Java.

Creating a thread in Java

There are two ways to create a thread in Java:
1) By extending Thread class.
2) By implementing Runnable interface.

Before we begin with the programs (code) of creating threads, let’s have a look at these methods of Thread class. We have used few of these methods in the example below.

  • getName(): It is used for Obtaining a thread’s name
  • getPriority(): Obtain a thread’s priority
  • isAlive(): Determine if a thread is still running
  • join(): Wait for a thread to terminate
  • run(): Entry point for the thread
  • sleep(): suspend a thread for a period of time
  • start(): start a thread by calling its run() method

Method 1: Thread creation by extending Thread class

Example :

Output:

Method 2: Thread creation by implementing Runnable interface

Example :

class MultiThread implements Runnable {

public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
}
}

public class JavaApplication4 {

public static void main(String[] args) {
Thread object = new Thread(new MultiThread());
object.start();
for (int i = 0; i < 10; i++) {
System.out.println("Main Thread id: " + Thread.currentThread().getId());
}
}
}

Output:

Main Thread id: 1
Thread 10 is running
Main Thread id: 1
Main Thread id: 1
Main Thread id: 1
Thread 10 is running
Thread 10 is running
Thread 10 is running
Thread 10 is running
Main Thread id: 1
Thread 10 is running
Main Thread id: 1
Main Thread id: 1
Main Thread id: 1
Main Thread id: 1
Main Thread id: 1
Thread 10 is running
Thread 10 is running
Thread 10 is running
Thread 10 is running

Awesome! You just learned how to use multi-threading in Java with some awesome examples.

Let`s have a look at some of it`s advantages and disadvantages.

Advantages of multithreading:

  • Enhanced performance by decreased development time
  • Simplified and streamlined program coding
  • Improvised GUI responsiveness
  • Simultaneous and parallelized occurrence of tasks
  • Better use of cache storage by utilization of resources
  • Decreased cost of maintenance
  • Better use of CPU resource

Disadvantages of multithreading:

  • Complex debugging and testing processes
  • Overhead switching of context
  • Increased potential for deadlock occurrence
  • Increased difficulty level in writing a program
  • Unpredictable results

This is how multithreading in java works. This brings us to the end of Java multithreading blog. I hope this was informative and helpful to you.

--

--