Multithreading in Java is a technique that allows multiple threads (smaller units of a process) to run concurrently within a program, thereby making better use of the CPU and improving the overall performance of an application. It allows multiple tasks to be executed at the same time in a single program, making it suitable for performing complex or resource-heavy tasks concurrently.
In Java, threads are lightweight processes, and each thread has its own execution path. Java provides built-in support for multithreading through the Thread class and the Runnable interface.
Java’s multithreading features effectively is to think concurrently rather than serially.
If you create too many threads, more CPU time will be spent changing contexts than executing your program!
Example: Using the Thread class
//Main.java file
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 2; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}
public class Main {
public static void main(String[] args) {
// Create two threads
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
// Start both threads
t1.start();
t2.start();
}
}
Output:
15 Value 1
14 Value 0
14 Value 1
Example: Using the Runnable interface
//Main.java file
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 2; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}
public class Main {
public static void main(String[] args) {
// Create a Runnable object
MyRunnable myRunnable = new MyRunnable();
// Create two threads using the Runnable object
Thread t1 = new Thread(myRunnable);
Thread t2 = new Thread(myRunnable);
// Start both threads
t1.start();
t2.start();
}
}
Output:
15 Value 1
14 Value 0
14 Value 1
Java Multithreading – Interview Questions
Q 1: What is multithreading in Java?
Q 2: Why is multithreading used?
Q 3: How does Java support multithreading?
Q 4: What is thread synchronization?
Q 5: Is Java multithreading platform-independent?
Java Multithreading – Objective Questions (MCQs)
Q1. What is the main advantage of multithreading in Java?
Q2. Which of the following statements about multithreading in Java is true?
Q3. Which of the following is not a way to create a thread in Java?
Q4. What is the purpose of the synchronized keyword in multithreading?
Q5. Which method is used to pause a thread until another thread finishes execution?