Java Multithreading
Definition of Multithreading: In Java, multithreading means running multiple “threads” (smaller units of a program) at the same time. Think of threads as workers; each one can do a different task in your program, allowing things to happen simultaneously. For example, one thread might be playing music while another is loading a file.
What is a Thread? A thread is a small part of a program that can run independently. It shares resources (like memory) with other threads, allowing the program to do more than one task at the same time.
Why Use Multithreading?
• Efficient CPU Use: It helps in using the computer’s processor more effectively.
• Better Performance: Threads share the same memory, so it’s faster than running separate programs for each task.
• Responsiveness: Multithreading helps programs feel smoother and respond quickly, like in games or apps with many things happening at once.
Creating Threads in Java
There are two main ways to create a thread in Java:
1. By Extending the Thread Class
2. By Implementing the Runnable Interface
1. Extending the Thread Class
When we create a thread by extending the Thread class, we write our task inside a special method called run().
Example:
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(“Running Thread: ” + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // Start thread1
thread2.start(); // Start thread2
}
}
Explanation:
• We create two threads (thread1 and thread2) using MyThread.
• start() tells each thread to begin running and calls run() automatically.
• Thread.sleep(1000); pauses each thread for 1 second in between prints.
2. Implementing the Runnable Interface
Instead of extending Thread, we can make our class implement the Runnable interface. This way, we pass our task to a new Thread object.
Example:
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(“Runnable Thread: ” + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnableTask = new MyRunnable();
Thread thread1 = new Thread(runnableTask);
Thread thread2 = new Thread(runnableTask);
thread1.start(); // Start thread1
thread2.start(); // Start thread2
}
}
Explanation:
• MyRunnable implements Runnable with its run() method.
• Thread thread1 = new Thread(runnableTask); connects runnableTask to thread1.
• Calling start() begins the thread.
Key Methods in Java Multithreading
• start(): Starts the thread and calls run().
• run(): Contains the code that the thread will execute.
• sleep(milliseconds): Pauses the thread for a set amount of time.
• join(): Makes one thread wait until another thread finishes.
Thread Synchronization
Synchronization is needed when multiple threads are sharing and updating the same data. It makes sure only one thread can access a piece of data at a time.
Example of Synchronization:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(“Count: ” + counter.getCount()); // Should print 2000
}
}
Explanation:
• The synchronized keyword in increment() makes sure only one thread can increase count at a time.
• thread1 and thread2 each increase count by 1000, so the result is 2000.
Tasks:
1. Write a Java program that creates two threads using the Thread class and prints their names along with a message.
2. Write a Java program that creates three threads using the Runnable interface, and each thread prints numbers from 1 to 5.
Course Video
YouTube Reference :
The training provides a basic introduction to Java multithreading, including concepts, benefits, and methods to create threads.
Yes, it includes examples demonstrating how to create threads by extending the Thread
class and implementing the Runnable
interface.
Yes, exercises involve creating and managing multiple threads to understand their behavior and synchronization.
Yes, it’s designed for beginners with clear explanations and step-by-step examples.
A Java IDE like Eclipse, IntelliJ IDEA, or an online compiler will suffice.
Yes, it covers how multithreading can lead to better CPU utilization, improved performance, and enhanced responsiveness in applications.
Yes, the training is self-paced and accessible online anytime.
Yes, it introduces the concept of thread synchronization to manage access to shared resources.
Yes, this Java Multithreading training is completely free on Iqra Technology Academy’s website.