Java Multithreading
Learn about Java Multithreading. Understand how to run multiple tasks simultaneously using Threads and the Runnable interface.
Multithreading allows your program to do multiple things at the same time.
Think of it like a Kitchen 🍳.
- Single-threaded: One chef doing everything. Chop onions -> Boil water -> Cook pasta. (Slow)
- Multi-threaded: Three chefs working together. Chef A chops, Chef B boils, Chef C cooks. (Fast!)
Creating a Thread
There are two ways to create a thread in Java.
1. Extend the Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the thread
System.out.println("This code is outside of the thread");
}
}2. Implement the Runnable Interface
This is the preferred way because you can still extend another class.
class MyRunnable implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
System.out.println("This code is outside of the thread");
}
}Concurrency Problems
When multiple threads access the same variable at the same time, problems can occur (Race Conditions).
Imagine two people trying to write in the same notebook at the same time. 📝💥 To fix this, we use Synchronization (taking turns).
public synchronized void increment() {
count++;
}Tip 💡: Always use start() to run a thread. If you call run(), it will execute like a normal method on the current thread, not a new one!
The volatile Keyword
The volatile keyword guarantees that the value of a variable is always read from the main memory, not from a thread's local cache. This ensures visibility of changes across threads.
private volatile boolean running = true;Inter-thread Communication
Threads can communicate using wait(), notify(), and notifyAll().
wait(): Causes the current thread to wait until another thread invokesnotify().notify(): Wakes up a single thread that is waiting on this object's monitor.
synchronized (lock) {
while (condition) {
lock.wait();
}
// do work
lock.notify();
}Which method starts the execution of a thread?
Note : Java is a statically-typed language. This means that all variables must be declared before they can be used.
Challenge
Complete this chapter to unlock the next one.
Challenge
Task:
Create a thread using a lambda expression that prints 'Running'. Start it.Key Takeaways
- Concurrency: Doing multiple things at the same time.
- Runnable: The preferred way to create threads (allows extending other classes).
- Synchronization: Prevents threads from interfering with each other.
Common Pitfalls
[!WARNING] Race Conditions: When two threads try to change shared data at the same time, the result is unpredictable. Use
synchronizedto fix this.Deadlocks: When Thread A waits for Thread B, and Thread B waits for Thread A. They wait forever!
What's Next?
How do we save data permanently? Learn File Handling →
