Multithreading introduction

Multithreading is one of the most popular feature of Java programming language as it allows the concurrent execution of two or more parts of a program. Concurrent execution means two or more parts of the program are executing at the same time, this maximizes the CPU utilization and gives you better performance. These parts of the program are called threads.

Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a process share the common memory. The process of executing multiple threads simultaneously is known as multithreading.

Advantages of Multithreading

  • Efficient CPU Utilization: As more than one threads run independently, this allows the CPU to perform multiple tasks simultaneously.
  • Improved Performance
  • Better Resource Sharing: As discussed earlier, threads share common memory, this reduces overhead compared to processes.

Creating Threads in Java

There are two primary ways to create threads:

1. By Extending the Thread Class

class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}

public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread and executes the `run` method
}
}

2. By Implementing the Runnable Interface

class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}

public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable);
t1.start(); // Starts the thread and executes the `run` method
}
}

Thread Methods

  • start(): Starts the thread, calling its run() method.
  • run(): Defines the code executed by the thread.
  • sleep(milliseconds): Pauses the thread for a specified duration.
  • isAlive(): Checks if the thread is still running.
  • getName() and setName(String name): To retrieve or set a thread’s name.

Comments