Multi-Threading in Java
- Zakee Ahmed
- Apr 6, 2020
- 1 min read
Background: High performance computing is utilization of many computing core in parallel way to get high throughput from an average performance computing cores. to do this, the program under execution (called a process) needs to be divided into concurrent set of sub-parts, called a Threads.
What is a Thread?
A thread is a light-weight smallest part of a process that can run concurrently with the other threads of the same process. as depicted in following figure

Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a process share the common memory. The process of executing multiple threads simultaneously is known as multi-threading. The threads can be feeded to multi core in following different schemes.

Why do we need Threads?
To enhance parallel processing
To increase response to the user
To utilize the idle time of the CPU
Prioritize your work depending on priority
Example
Consider a simple web server. The web server listens for request and serves it. If the web server was not multi-threaded, the requests processing would be in a queue, thus increasing the response time and also might hang the server if there was a bad request.
By implementing in a multi-threaded environment, the web server can serve multiple request simultaneously thus improving response time

How to write Multi-Threading program with Java?
Java provides two approaches to write a multi threaded class. one is by using a class named 'Thread', or by using an interface called 'Runnable'.
Example: Thread Class

Example: Runnable Interface

Comments