Welcome to this comprehensive guide on Java Multithreading! Let's embark on a journey to understand one of the most powerful features of Java that enables efficient and concurrent execution of multiple tasks. 📝
Multithreading is a process where multiple threads run concurrently within a program. Each thread performs a specific task independently. This feature allows Java programs to be more efficient, responsive, and capable of handling multiple tasks at the same time.
Java provides several ways to create threads, but the most common methods are:
Thread ClassRunnable InterfaceThread Class 📝public class MyThread extends Thread {
public void run() {
System.out.println("This is my thread!");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Start the thread
}
}Runnable Interface 📝public class MyRunnable implements Runnable {
public void run() {
System.out.println("This is my runnable thread!");
}
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start(); // Start the thread
}
}In multithreading, synchronization is necessary to ensure that only one thread accesses shared resources at a time to avoid conflicts and inconsistencies.
Java provides synchronized keyword and Lock interface for synchronization.
public class MySync {
synchronized void printNumber(int number) {
for (int i = 1; i <= 5; i++) {
System.out.println(number + "-" + i);
try {
Thread.sleep(1000); // Simulate delay
} catch (Exception e) { }
}
}
public static void main(String[] args) {
MySync obj = new MySync();
Thread t1 = new Thread(() -> obj.printNumber(1));
Thread t2 = new Thread(() -> obj.printNumber(2));
t1.start();
t2.start();
}
}In the above example, both threads access the printNumber method, which is synchronized. Therefore, only one thread can execute the method at a time.
The Producer-Consumer problem is a classic example of synchronization in multithreading. It simulates a scenario where one thread (Producer) produces data and another thread (Consumer) consumes the data.
Here's a simple implementation using a Buffer class and synchronized methods:
public class Buffer {
private int bufferSize = 5;
private int buffer[] = new int[bufferSize];
private int count = 0;
private int producer = 0;
private int consumer = 0;
public synchronized void put(int data) throws InterruptedException {
while (count == bufferSize) {
wait();
}
buffer[producer] = data;
producer = (producer + 1) % bufferSize;
count++;
notifyAll();
}
public synchronized int get() throws InterruptedException {
while (count == 0) {
wait();
}
int data = buffer[consumer];
consumer = (consumer + 1) % bufferSize;
count--;
notifyAll();
return data;
}
}What is the primary purpose of using Multithreading in Java?
How can you create a thread in Java?