Thread

Imagine trying to download something, and your mouse freezes, preventing you from doing anything else. Why does this happen? In today's computers, it's because the operating system is running multiple processes simultaneously.

Concepts

Process

A running program, meaning a program that the user has written, is allocated memory space and executed by the operating system. This process consists of resources such as data, memory, and threads.

Thread

A thread is the entity that actually performs the work within a process. Every process has at least one thread. If a process has only one thread, it's called single-threaded; if it has more than one thread, it's called multi-threaded.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/b6c6ea5a-67bf-4ea8-9cf9-5ec01401af70/Untitled.png

Implementation and Execution

Method 1: Extending Thread Class

Java allows only single inheritance, making this method less commonly used.

class ThreadWithClass extends Thread {
    public void run() // Override the run() method of the Thread class
    // Work to be done in the thread
}
ThreadWithClass thread1 = new ThreadWithClass(); // Create a thread
thread1.start(); // Start the thread

class ThreadWithClass extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(getName()); // Returns the name of the currently executing thread.
        }
    }
}

Method 2: Implementing the Runnable Interface

As Java supports multiple interfaces, this method provides more flexibility.

class ThreadWithRunnable implements Runnable {
    public void run() // Implement the run() method of the Runnable interface
    // Define the work to be done in the thread
}
Thread thread2 = new Thread(new ThreadWithRunnable());
thread2.start(); // Start the thread

class ThreadWithRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()); // Returns the name of the currently executing thread.
        }
    }
}