Simplifying Java Multithreading (Runnable interface) with a Construction Analogy
Tags: java, javathreads, multithreading, parallelprogramming
Published: 2023-09-08 18:31:17

# **Multi-Threaded Program in Java -**

Imagine you're in a kitchen, trying to prepare a meal. You have a single cutting board and knife, and you need to chop vegetables, boil pasta, and cook a sauce all at the same time. If you were to do each task one after the other, it would take a long time to finish the entire meal.

Now, let's relate this to programming in Java:

## **Single Threaded Programming:**:
![Single chef](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/826uyexqga957jvnewy3.jpeg)
This is like having only one chef in the kitchen doing all the cooking. The chef starts chopping vegetables, then waits for that to finish, then starts boiling pasta, and so on. It's slow and not very efficient.


## **Multi-Threaded Programming:**:

![Multiple chefs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9506ozssoz35dygfeesf.png)
In this case, it's as if you have multiple chefs in the kitchen, each with their own cutting board and knife. They can work on different tasks simultaneously. One chef can chop vegetables, another can boil pasta, and another can work on the sauce, all at the same time. This makes the cooking process much faster and more efficient.

In Java, `multi-threaded programming` allows you to have multiple `"threads"` (similar to chefs) running concurrently within a program. Each thread can perform a specific task independently, and they can work together to complete a larger task more quickly, just like the chefs in the kitchen. This can lead to better performance and responsiveness in Java applications, especially when dealing with tasks that can be done simultaneous

# **How to create a Multi-Threaded Program -**

> When thinking of creating a Multi-Threaded Program, never think in terms of what Threads you need to create!
Rather think in terms of what TASKS that needs to be done in parallel.
>

Let’s understand the steps to create a multi-threaded program by taking an analogy of a construction site with different workers such as painters, carpenters, electricians etc. 


![construction site](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpa4zguy5qw19jtr0xlo.jpeg)

## **Steps to create:**
Let's explore the simple steps to create a multi-threaded program now.

### 1. **Define Task Classes**

Create a `class` for each `task` you want to perform. Think of these classes as workers, and name them as **nouns** to represent the tasks they'll handle.

> **Analogy:** Imagine you're managing a construction site. You have different types of workers like "Carpenter," "Painter," and "Electrician" for specific jobs.
>

### 2. **Implement the Runnable Interface**

For every task class, implement the **`Runnable`** interface. This ensures that each class has a **`run`** method, which will contain the code for the task.

> **Analogy:** Think of the **`Runnable`** interface as a set of instructions that every worker (task class) must follow
>

```
class CarpenterTask implements Runnable {
    public void run() {
        // Code for carpentry work
    }
}

class PainterTask implements Runnable {
    public void run() {
        // Code for painting work
    }
}
```

### 3. **Code Task Logic**

Inside each task's **`run`** method, write the code that the task needs to perform. This is where you specify what each worker should do.

> **Analogy:** In our construction site, the **`run`** method of the `CarpenterTask` class would contain the actual carpentry work instructions.
>

```
class CarpenterTask implements Runnable {
    public void run() {
        System.out.println("The carpenter is drilling and fixing screws");
    }
}

class PainterTask implements Runnable {
    public void run() {
        System.out.println("The Painter is painting the walls and windows");
    }
}
```

### 4. **Create Task Instances**

Instantiate the task classes wherever you want to start a new thread for that task. Think of this as hiring a worker for a specific job.

> **Analogy:** You hire a carpenter when you need carpentry work and a painter when you need painting.
>

```
public class Main{
	public static void main(String[] args){

		//Create the instances of the tasks in the main 
		CarpenterTask carpenter = new CarpenterTask();
		PainterTask painter = new PainterTask();

	}
}
```

### 5. **Create Thread Objects**

Create `thread` objects for each task instance you created. `Threads` are like supervisors that manage the workers (task instances).

> **Analogy:** You assign a supervisor to each worker to oversee their tasks.
>

```
public class Main{
	public static void main(String[] args){

		//Create the instances of the tasks in the main 
		CarpenterTask carpenter = new CarpenterTask();
		PainterTask painter = new PainterTask();

		//Create the Thread Objects
		Thread carpenterThread = new Thread(carpenter);
		Thread painterThread = new Thread(painter);

	}
}
```

### 6. **Start the Threads**

Finally, start the threads using the **`start()`** method. This kicks off the tasks, and the workers (threads) begin working concurrently.

> **Analogy:** You tell the supervisors to start overseeing their workers, and each worker begins their assigned task.
>

```
public class Main{
	public static void main(String[] args){

		//Create the instances of the tasks in the main 
		CarpenterTask carpenter = new CarpenterTask();
		PainterTask painter = new PainterTask();

		//Create the Thread Objects
		Thread carpenterThread = new Thread(carpenter);
		Thread painterThread = new Thread(painter);
		
		//Start the threads
		carpenterThread.start();
		painterThread.start();

	}
}
```
With these steps, you've created a multi-threaded program in Java where different tasks are performed concurrently, just like different workers at a construction site simultaneously working on carpentry and painting tasks.

## **How to Check Thread Names in Java?**

In a multi-threaded Java program, you can easily obtain the name of the currently executing thread by calling **`Thread.currentThread().getName()`**. This allows you to identify which thread is executing a particular task. 

Let's see how to do this in the context of our Carpenter and Painter tasks:

```
class CarpenterTask implements Runnable {
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("Carpenter task is being executed by thread: " + threadName);
        // Code for carpentry work
    }
}

class PainterTask implements Runnable {
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("Painter task is being executed by thread: " + threadName);
        // Code for painting work
    }
}

//Expcted Output -
//Carpenter task is being executed by thread: Thread-0
//Painter task is being executed by thread: Thread-1
```

In the above code, we've added lines to print the thread name within each task's **`run`** method using **`Thread.currentThread().getName()`**.

In this example, "`Thread-0`" represents the thread executing the Carpenter task, and "`Thread-1`" represents the thread executing the Painter task. The thread names are generated automatically by Java, and they typically have a format like "`Thread-X`," where X is a unique identifier for each thread.


### **Closing Thoughts:**
Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you'd like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.

Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.