Home Java Tutorial Multithreading in Java

Multithreading in Java

by anupmaurya
2 minutes read

What is Multithreading in Java?

Multithreading in Java is a process of executing two or more parts of a program, simultaneously to maximum utilization of CPU.

  • Each part of such a program is called a thread. So, threads are light-weight processes within a process.
  • 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. Multiple threads don’t allocate separate memory areas, hence they save memory. Also, context switching between threads takes less time.
  • Java Multithreading is mostly used in animation, games, etc.

To understand this better, think of you are playing a car racing game ,and each player is a thread of same game.

Advantages of multithread

  1. The users are not blocked because threads are independent, and we can perform multiple operations at times
  2. Threads are independent, so it doesn’t affect other threads if an exception occurs in a single thread.
  3. You can perform many operations together, so it saves time.

Example of Multithread

class MultithreadingExample implements Runnable  {
  	public void run()
	{
		try {
			// Displaying the thread that is running
			System.out.println(
				"Thread " + Thread.currentThread().getId()
				+ " is running");
		}
		catch (Exception e) {
			// Throwing an exception
			System.out.println("Exception is caught");
		}
	}
}

public class TestThread {

  	public static void main(String[] args)
	{
		int n = 6; // Number of threads
		for (int i = 0; i < n; i++) {
			Thread object
				= new Thread(new MultithreadingExample());
			object.start();
		}
	} 
}

Output

Thread 21 is running 
Thread 22 is running 
Thread 23 is running 
Thread 24 is running 
Thread 25 is running 
Thread 26 is running

What is Multitasking?

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways:

  • Process-based Multitasking (Multiprocessing)
  • Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

  • Each process has an address in memory. In other words, each process allocates a separate memory area.
  • A process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • A thread is lightweight.
  • The cost of communication between the thread is low.

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.