-->

Java - Threads Part 1: Introduction to Threads

A thread is a lightweight sub-process, the smallest unit of execution in Java. Threads can be created and executed using the Thread class or implementing the Runnable interface.

Examples and Explanation

Creating a Thread 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 thread = new MyThread();

        thread.start();

    }

}

Explanation: The run() method defines the task to be performed, and start() begins the thread execution.

Creating a Thread by Implementing Runnable

class MyRunnable implements Runnable {

    public void run() {

        System.out.println("Runnable thread is running...");

    }

}

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(new MyRunnable());

        thread.start();

    }

}

Explanation: Implementing Runnable provides more flexibility, such as extending another class while defining the thread.

Using Lambda Expressions with Threads

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(() -> System.out.println("Thread with lambda running..."));

        thread.start();

    }

}

Explanation: Lambda expressions simplify thread creation for concise and readable code.