Java Basics of Multithreading

Multithreading in Java allows concurrent execution of multiple threads within a program. It enhances the performance and responsiveness of applications by efficiently utilizing CPU resources.

Creating Threads:

There are two main ways to create threads in Java: by extending the Thread class or by implementing the Runnable interface.

Extending Thread Class:


// Extending Thread class
class MyThread extends Thread {
  public void run() {
    // Code to be executed in a separate thread
    for (int i = 0; i < 5; i++) {
      System.out.println("Thread 1: " + i);
    }
  }
}

public class ThreadExample {
  public static void main(String[] args) {
    // Create an instance of the custom thread
    MyThread thread1 = new MyThread();

    // Start the thread
    thread1.start();

    // Code in the main thread
    for (int i = 0; i < 5; i++) {
      System.out.println("Main Thread: " + i);
    }
  }
}

Implementing Runnable Interface:


// Implementing Runnable interface
class MyRunnable implements Runnable {
  public void run() {
    // Code to be executed in a separate thread
    for (int i = 0; i < 5; i++) {
      System.out.println("Thread 2: " + i);
    }
  }
}

public class RunnableExample {
  public static void main(String[] args) {
    // Create an instance of the custom runnable
    MyRunnable myRunnable = new MyRunnable();

    // Create a thread using the runnable
    Thread thread2 = new Thread(myRunnable);

    // Start the thread
    thread2.start();

    // Code in the main thread
    for (int i = 0; i < 5; i++) {
      System.out.println("Main Thread: " + i);
    }
  }
}

Thread Lifecycle:

Threads go through various states in their lifecycle, including New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated.

Synchronization:

Synchronization is important to ensure that multiple threads don't interfere with each other while accessing shared resources. It can be achieved using the synchronized keyword or Lock interfaces.

Note:

Multithreading introduces the concept of shared resources and the need for synchronization to prevent race conditions and data inconsistencies.