Understand the difference between Multithreading and Multitasking in Java, their advantages, limitations, and how they improve program efficiency and responsiveness.
Multithreading in Java allows concurrent execution of two or more threads within a single program. Each thread performs a specific task, helping achieve parallel execution for better performance.
class Task1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 1 - Count: " + i);
}
}
}
class Task2 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 2 - Count: " + i);
}
}
}
public class MultiThreadExample {
public static void main(String[] args) {
Task1 t1 = new Task1();
Task2 t2 = new Task2();
t1.start();
t2.start();
}
}
Output: Both threads run concurrently, displaying interleaved results.
Multitasking means the ability of an operating system to execute multiple programs or processes simultaneously. Java supports multitasking using process-based and thread-based multitasking.
Running a Java program while listening to music and downloading a file — all at the same time. Each task runs independently in separate processes handled by the OS.