Multithreading is a concept in java that offers concurrency (even parallellism if working on quad-core processor).
Thread can be thought as the smallest unit of code and with the help of multithreading we can work on multiple threads concurrently.
Think of a shop for instance that has only one person for assistance, if multiple customers come to a shop then instead of fullfilling their needs one by one i.e. listening to their needs, then waiting for the processing of the product and then giving it to customer and later going to another customer its better to get the requests from other customers while the processing takes place.
This is what we can achieve by multithreading, executing multiple threads concurrently, and switching between threads while one is stuck in a process.
Code:
Firstly when we make a class such that we want to perform multithreading we extend the class Thread which is a built in class in java.
To perform multithreading we use the method run() which again is a method of class Thread that we override in our classes.
Even if we create other methods in the class, to perform them in multithreaded manner we must declare them inside the run() method.
At the time of creating objects of the class and calling the methods we use obj.start(). The start() method is the basis of multithreading and it calls the run() method.
The start() method creates a new thread that can be concurrently run. If we do not call the start method and directly call any other method (even run() ) then the code is executed in sequential manner.
Output:
This is a part of output, where we can clearly see that instead of running the first line for 50 times and then executing the other statement both the statements are being executed concurrently.
I used the for loop for 50 statements as the processing happens so quickly that if the statements were to be printed only a few number of times they might have appeared almost sequential.
Doubts:
Now lets discuss some doubts that might come in our mind as a beginner.
First:Does start() only calls run() method?
Answer: Yes it only calls run() so if any other method is to be made it needs to be either declared inside of run() or called separately. But calling it separately in main thread (main class) makes it sequential.
Second: what if we create a method apart form run().
Answer: In that case we will have to declare the method in the run() method as well, so that when we call start(), all the part of run() of run() is executed including the other methods mentioned in it
in this manner doWork() would also be executed along with run().
Top comments (0)