GFG Day 16: Introduction to Multithreading

sri parthusri parthu
4 min read
  • Multithreading is a process of executing two or more threads simultaneously to achieve concurrent execution. A thread is the smallest unit of a process. Multithreading makes the program faster and efficient by doing multiple tasks in parallel.

  • Example: Consider a kitchen in a restaurant where several chefs are preparing several dishes at once. Similar to Java threads, this arrangement ensures better CPU (chef) use and faster service.

thread

Implementation:

class CookingTask extends Thread {
    private String task;

    CookingTask(String task) {
        this.task = task;
    }

    public void run() {
        System.out.println(task + " is being prepared by " +
            Thread.currentThread().getName());
    }
}

public class Restaurant {
    public static void main(String[] args) {
        Thread t1 = new CookingTask("Pasta");
        Thread t2 = new CookingTask("Salad");
        Thread t3 = new CookingTask("Dessert");
        Thread t4 = new CookingTask("Rice");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

Output

Dessert is being prepared by Thread-2
Salad is being prepared by Thread-1
Rice is being prepared by Thread-3
Pasta is being prepared by Thread-0

Explanation:

  • By extending the Thread class, the application generates multiple threads (CookingTask).

  • Pasta, salad, and other dishes are represented by each thread.

  • To enable concurrent task execution,.start() is used to launch threads t1 through t4.

Different Ways to Create Threads

Threads can be created by using two mechanisms:

  1. Extending the Thread class

  2. Implementing the Runnable Interface

1. By Extending the Thread Class

  • A class that extends the java.lang.Thread is created. class of thread. The Thread class's run() method is overridden by this class. The run() method is where a thread starts. To begin a thread's execution, we create an object of our new class and invoke the start() method. The Thread object's run() method is called by start().

Example: Creating a Thread by extending the Thread class.

class Multithreading extends Thread {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {

            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}

// Main Class
public class Main
{
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            Multithreading object
                = new Multithreading();
            object.start();
        }
    }
}

Output

Thread 13 is running
Thread 14 is running
Thread 12 is running
Thread 11 is running
Thread 16 is running
Thread 15 is running
Thread 18 is running
Thread 17 is running

2. By Implementing the Runnable Interface

  • A new class that implements java.lang.Runnable is created. Define the run() method in the runnable interface. Next, we create a Thread object and invoke its start() method.

Example: Demonstrating the multithreading by implementing the Runnable interface.

class Multithreading implements Runnable {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {

            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}

// Main Class
class Main {
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            Thread object
                = new Thread(new Multithreading());
            object.start();
        }
    }
}

Output

Thread 12 is running
Thread 15 is running
Thread 18 is running
Thread 11 is running
Thread 17 is running
Thread 13 is running
Thread 16 is running
Thread 14 is running

Thread Class vs Runnable Interface

  • The following table tells the key differences between the two approaches
AspectThread ClassRunnable Interface
InheritanceWe need to extend a Thread class. Because it is a class. It means we can not add any other class if we extend it.It is a interface so use using the implent keyword and allows us to use other classes as well.
Thread SharingThe Thread object cannot be sharing among the different multiple threads.The object of Runnable interface can be shared among different threads.
ImplementationWe can override the run() method present in the Thread class.We can implement the run() method present in the Runnable interface.
Built-in MethodsIt provides methods like yield(), interrupt() and getId etc.These methods are not present in the Runnable interface .

Happy Learning

Thanks For Reading! :)

SriParthu ๐Ÿ’๐Ÿ’ฅ

0
Subscribe to my newsletter

Read articles from sri parthu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sri parthu
sri parthu

Hello! I'm Sri Parthu! ๐ŸŒŸ I'm aiming to be a DevOps & Cloud enthusiast ๐Ÿš€ Currently, I'm studying for a BA at Dr. Ambedkar Open University ๐Ÿ“š I really love changing how IT works to make it better ๐Ÿ’ก Let's connect and learn together! ๐ŸŒˆ๐Ÿ‘‹