Understanding Multi-threading In Java With Practical Example

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’

public class Main extends Thread {

    public void run(){
        System.out.println("Thread is running in background.");
    }
    public static void main(String[] args) {
        Main thr1 = new Main();
        thr1.start();
    }
}

In this example, we’re using the Main class and extending it to Thread class. run() function becomes mandatory when we do so. In the main function, we create a new object of our class and start the thread using start() function.

Output: Thread is running in background.

 

Creating A Thread Using Runnable Interface

 

public class Main implements Runnable {

    public void run(){
        System.out.println("Thread is running in background.");
    }
    public static void main(String[] args) {
        Main mainobj = new Main();
        Thread t = new Thread(mainobj);
        t.start();
    }
}

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

Downloading multiple files simultaneously using Multithreading

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.

Related posts