Multithreading means doing many tasks at the same time in a single program.
Each task runs in a thread (like a small worker in a factory).
For example:
Java gives two main ways to create a thread:
Thread
classclass MyThread extends Thread {
public void run() {
System.out.println("This is my thread running");
}
}
MyThread t = new MyThread();
t.start(); // Start the thread
Runnable
interfaceclass MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
โ
Tip: Use Runnable
if you want to extend another class too (Java allows only one superclass).
Just like humans are born, grow, and die โ threads also have stages:
New โ Ready โ Running โ Waiting โ Dead
Stage | What happens? |
---|---|
New | Thread is created |
Ready | Ready to run but waiting for CPU |
Running | It is running now |
Waiting | Waiting for something to finish |
Dead | Finished its task |
Every thread has a priority from 1 to 10.
Higher number = more important (but not always guaranteed to run first).
Thread t = new Thread();
t.setPriority(10); // Highest
Note: Java tries to give more time to important threads, but it's up to the OS.
Imagine 2 people writing on the same paper at the same time โ messy, right?
If two threads change the same data, they can cause problems.
We use synchronization to let only one thread use it at a time.
synchronized void deposit() {
// only one thread can enter here at a time
}
Sometimes, one thread must wait for another to finish something.
Example:
We use:
wait()
โ pause the threadnotify()
โ wake up one threadnotifyAll()
โ wake up all waiting threadsThese must be used inside synchronized
blocks!
Deadlock happens when two threads are waiting for each other, and no one continues.
// Thread A locks Pen, then wants Notebook
// Thread B locks Notebook, then wants Pen
tryLock()
Instead of making threads manually, Java gives you an Executor (like a smart thread manager).
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
System.out.println("Doing work using Executor");
});
executor.shutdown();
Concept | Simple Meaning |
---|---|
Thread | A mini-program running inside your main program |
Runnable | A way to make a class โthreadableโ |
Synchronization | Stops two threads from using the same thing at the same time |
wait/notify | One thread can pause and wait for another |
Deadlock | Two threads stuck waiting for each other |
Executor | A smart manager that handles threads for you |