Vikas Rajput
Vikas Rajput

@vikasrajputin

12 تغريدة 1 قراءة Oct 17, 2022
Multithreading is one of the highly asked questions in Java Interview
Here're 8 simple steps to explain Multithreading to anyone🧵👇
1. What is Multithreading?
- It's a concept of applying multitasking in Java.
- Java supports thread-based multitasking.
- Java program can be divided into several threads and those threads can be executed in parallel to support multitasking.
2. Two Ways to Create a Thread
- By Implementing a Runnable Interface
- By extending the Thread class
3. Creating Thread via "Runnable" interface
- Steps:
a. Implement Runnable Interface
b. Override the run() method, and put your code inside it.
c. Pass the instance of your class to the Thread class constructor.
d. Call the start() method to run your thread.
4. Creating Thread via "Thread" class:
- Steps:
a. Extend your class with Thread class
b. Override the run() method, and put your code inside it.
c. Instantiate your class.
d. Call the start() method to run your thread.
5. Which is the Best Approach?
- It is always advisable to use the first approach(By implementing a Runnable Interface) to create the threads in Java.
- Because it's an Interface, you can also extend other classes in the future and also implement other interfaces.
6. Lifecycle of thread:
- It has 5 different phases in its lifecycle:
a. New
b. Runnable
c. Running
d. Waiting
e. Dead
7. Few Important Methods of Thread Class:
run() - Actual task of the thread is defined here.
start() - Starts the thread
join() - Wait for thread to die.
setName() - Give name to our thread.
getName() - Returns the thread name.
setPriority() - Sets the priority to thread.
getPriority() - Returns the priority.
getState() - Returns the state of thread.
isAlive() - checks if thread is alive or not
and a few more...
8. Conclusion:
- We can use Multithreading in order to boost the performance of our program.
- If our program has independent units, we can run those independent code blocks into a separate thread.
- They can run parallel and process faster than normal.
That's a wrap!
Every Mon, Wed & Friday - I tweet a thread on Backend Development.
Follow me
@vikasrajputin
to read all my future threads.
Before you go, do you know?
I've also started writing on LinkedIn
I share some exclusive content there, which I never share here.
Follow me on Linkedin to stay updated with Backend content:
linkedin.com

جاري تحميل الاقتراحات...