In this article, we will cover the concept of Thread. How to create Thread and use it.
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. For example, you are working on your system and simultaneously you are running one process like excel and parallelly you are also listening music and surfing internet. So this is multitasking accessing more than one application or process at same time. Multitasking can be achieved by two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
In process-based multitasking, each process allocate separate memory area because each process has its own address in the memory area.
A Process is heavyweight.
Cost of communication between the process is high.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A Thread is lightweight.
Cost of communication between the thread is low.
Multithreading is the capability of a program to direct its use by more than one user and even to manage multiple requests by the same user. In the java, simultaneous programming is mostly concerned with threads. However, processes are also important.
Process and Thread:
a process is an execution of a program and a thread is a single execution of work within the process. A process can contain multiple threads. A thread is also known as a lightweight process.
Java Multithreading is mostly used in games, animation etc.
Watch the video on YouTube –
How to implement thread:
There are two ways to create a thread
1) extends thread class
2) implements runnable interface
let’s see how to define a single thread in java.
Using first ways:- extends thread class:
It should override the run() method and provide its own implementation of run().the start() method in the code starts the execution of a thread.
Now another way is to implement a runnable interface: that provides its own implementation of run() method.
we use multithreading than multiprocessing because threads share a common memory area. They don’t allocate separate memory area, as a result, saves memory.
Hope this articles helps you understand the concept of Multithreading better. Let us know if you have any suggestions about the content in the comment section below.