1. Introduction to Multithreading
Before we start writing any multithreading code, let's understand why we need multithreading in the first place.
Imagine you are using an online shopping application.
You open the application and start browsing products. At the same time, the application might be doing several things behind the scenes:
- Loading product information.
- Fetching product images.
- Checking your shopping cart.
- Getting recommendations for you.
- Checking whether your session is still active.
Now imagine if the application had to complete every single task one by one before starting the next task.
Would that be a good experience?
Probably not!
You might have to wait for one task to finish before another task could even begin.
This is where multithreading becomes useful.
Multithreading allows a program to have multiple threads working on different tasks, instead of making everything happen through just one thread.
2. How Does a Normal Java Program Execute?
Let's first understand how a simple Java program works without creating any additional threads.
Consider the following program:
public class Main {
public static void main(String[] args) {
System.out.println("Preparing the order");
System.out.println("Packing the order");
System.out.println("Dispatching the order");
}
}
What do you think will happen when we execute this program?
The statements will execute one after another.
First, the program prints:
Preparing the order
Then it prints:
Packing the order
Finally, it prints:
Dispatching the order
The output will be:
Preparing the order
Packing the order
Dispatching the order
Notice that the second statement starts only after the first statement finishes.
Similarly, the third statement starts only after the second statement finishes.
This is called sequential execution.
One task executes after another. The next task waits for the previous task to finish.
3. Can We Perform Different Tasks at the Same Time?
Let's take a simple example from everyday life.
Imagine you are preparing tea and snacks for your guests.
You have two tasks:
- Prepare tea.
- Prepare snacks.
Let's say preparing tea takes five minutes and preparing snacks also takes five minutes.
If you prepare tea first and then start preparing snacks, you will spend ten minutes in total.
But what if you start preparing tea and, while it is boiling, you start preparing snacks?
You are now managing both activities together.
You do not necessarily have to wait for one activity to finish before beginning the other.
This is the basic idea behind concurrent execution.
Multiple tasks make progress during the same period of time. A processor may switch between tasks, allowing them to progress together.
In a Java application, multiple threads help us achieve this kind of execution.
4. What Exactly Is a Thread?
Now let's understand the most important word in this course: Thread.
Think of a thread as a worker who performs a particular task.
Imagine a restaurant with three workers:
- One worker takes customer orders.
- One worker prepares food.
- One worker handles billing.
All three workers are working for the same restaurant, but each one has a different responsibility.
Similarly, a Java program can have multiple threads. Each thread can execute a different piece of work.
A thread is simply an independent path of execution within a program.
A thread is an independent path of execution within a Java program.
We will learn how to create these workers, or threads, in our next class.
5. What Is the Main Thread?
There is something interesting about Java programs.
Whenever we start a Java application, Java creates a thread to execute our main() method.
We call this thread the main thread.
Consider this familiar program:
public class Main {
public static void main(String[] args) {
System.out.println("Hello Java!");
}
}
The main thread is responsible for executing the statements inside main().
Later, we will learn how to create additional threads so that our application can perform more work.
For now, just remember:
- A Java program starts with the main thread executing main().
- We can create additional threads when required.
6. Why Do We Need Multithreading?
Let's return to our online shopping application.
Imagine that the application needs to load product details, fetch images, and check your shopping cart.
If everything is handled sequentially, one task may have to wait for another.
With multiple threads, the application can make progress on different tasks during overlapping periods of time.
This can help applications:
- Handle multiple activities more efficiently.
- Remain responsive while background work happens.
- Make better use of available processor resources.
- Handle multiple requests in server applications.
This is why multithreading is an important concept in Java development.
7. Does Multithreading Always Make a Program Faster?
This is an important question.
You might think that if we create more threads, our application will always become faster.
But that is not necessarily true.
Creating and managing threads also takes resources. If we create too many threads, our application may actually become slower.
Also, when multiple threads access the same data, problems can occur if we do not manage that data properly.
Let's take a very simple example.
Imagine two workers are updating the same customer account balance.
Both workers read the same old balance, make their own changes, and then save the result.
One worker's update might overwrite the other worker's update.
This kind of problem is called a race condition.
Don't worry about solving this problem yet. We will dedicate separate classes to understanding shared data and race conditions.
Multithreading is powerful, but we must use it carefully. More threads do not automatically mean better performance.
8. Concurrency vs. Parallelism
These two words are often used together. Let's understand the difference in simple terms.
Concurrency
Multiple tasks make progress during the same period of time.
Imagine one chef preparing two dishes. The chef works on one dish, switches to the other, and continues switching as needed.
Both tasks make progress, even though the chef is handling them one at a time.
Parallelism
Multiple tasks are actually executing at the same moment, using different processing resources.
Imagine two chefs preparing two different dishes at exactly the same time.
Both are working simultaneously.
- Concurrency means managing multiple tasks whose execution overlaps.
- Parallelism means executing multiple tasks at the same moment.
We will explore these ideas further as we progress through the course.
9. What Will We Learn in This Course?
Today, we have only scratched the surface of multithreading.
Throughout this course, we will gradually learn:
- How to create threads in Java.
- How threads execute and communicate.
- How multiple threads share data.
- How to prevent problems such as race conditions.
- How to manage threads using thread pools.
- How to coordinate multiple threads.
- How to use modern Java concurrency features.
- How to build multithreaded applications.
We will take each concept one class at a time. There is no need to understand everything today.
10. Test Your Understanding
Let's see how much you understood from today's class! Read each question carefully and select the answer you think is correct. You will get immediate feedback after selecting an option. Don't worry about making mistakes. They are part of learning!
What is sequential execution?
What is a thread in Java?
Which thread executes the main() method when a Java application starts?
What does concurrency allow a program to do?
What is parallelism?
Does creating more threads always make an application faster?
11. Closing Words
That's it for our first class!
Today, we understood what threads are, why multithreading is useful, and the difference between sequential execution, concurrency, and parallelism.
We also learned that every Java application starts with a main thread.
Remember, we are not in a hurry. Our goal is to understand every concept properly.
In our next class, we will write our first multithreading program and learn how to create a new thread using Java's Thread class.
Keep practising, stay curious, and enjoy learning!
Lots of love,
Ankit Khera
Full Stack School