Multithreading is a feature in Java that allows a program to execute multiple tasks (threads) simultaneously.
👉 A thread is the smallest unit of execution within a program.
| Feature | Process | Thread |
|---|---|---|
| Definition | Independent program | Part of process |
| Memory | Separate | Shared |
| Communication | Difficult | Easy |
| Speed | Slower | Faster |
Flow:
New → Runnable → Running → Waiting → Running → Terminated
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // starts thread
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}
public static void main(String[] args) {
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj);
t.start();
}
}
| Thread Class | Runnable Interface |
|---|---|
| Uses inheritance | Uses interface |
| Cannot extend another class | Can extend another class |
| Method | Purpose |
|---|---|
start() |
Starts thread |
run() |
Contains code |
sleep() |
Pause thread |
join() |
Wait for thread |
isAlive() |
Check status |
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
t.setPriority(Thread.MAX_PRIORITY);
Synchronization is used to control access of multiple threads to shared resources.
👉 Prevents data inconsistency
class Table {
synchronized void printTable(int n) {
for(int i=1; i<=5; i++) {
System.out.println(n*i);
}
}
}
wait()notify()notifyAll()👉 Used for coordination between threads
A deadlock occurs when two or more threads wait for each other forever.
start() (not run() directly)Thread = smallest unit of execution
Multithreading = multiple threads running
Methods:
Key concepts:
Open this section to load past papers