Multithreading in Java allows multiple threads to work at same time. Threads can be described as the small units which work in the background. They work in a way such that main interface of an application doesn’t hang. Multithreading makes Java a lightweight processing language.
Threads make it possible for heavy applications to work smoothly. You can perform tasks simultaneously so threads save your time. For example, if you are making a downloader, you wish to implement multiple downloads simultaneously. No one wants to download one file, then another, then another and so on. This way thread is absolutely time-saving.
Creating A Thread Using ‘Extends’
Creating A Thread Using Runnable Interface
We can use interface using ‘implements’ keyword. We create a new object named mainobj of our class and create a new thread while passing the main class object. Then similarly we start the thread. The output is same as above.
Runnable is an interface and represents a task in Java. It defines only one method run(). This method is executed as soon as thread is started.
Example: CDLU Mathematics Hub
For an example, I will use my own android app CDLU Mathematics Hub. This app allows you to download multiple study resources simultaneously. Actually, the app is using Service class from Android SDK which in turn create multiple threads to handle simultaneous downloads which you can see in the screenshot above. Thread manages it perfectly in the background so that main application doesn’t hang.