How to Create and Start a Thread in Java

Introduction

Multithreading in Java allows multiple threads to run concurrently, enabling the execution of multiple tasks simultaneously. Threads are lightweight processes within a program that share the same memory space. This guide will cover the basics of creating and starting a thread in Java using two main approaches: extending the Thread class and implementing the Runnable interface.

Table of Contents

  1. Introduction to Threads
  2. Creating a Thread by Extending the Thread Class
  3. Creating a Thread by Implementing the Runnable Interface
  4. Using Lambda Expressions to Create Threads
  5. Common Thread Methods
  6. Example Programs
  7. Conclusion

1. Introduction to Threads

A thread is a lightweight process that can run concurrently with other threads. Java provides built-in support for multithreading through the java.lang.Thread class and the java.lang.Runnable interface. Multithreading can improve the performance of applications by making better use of system resources.

2. Creating a Thread by Extending the Thread Class

One way to create a thread in Java is by extending the Thread class and overriding its run method.

Example:

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

    public static void main(String[] args) {
        MyThread thread = new MyThread(); // Create a thread object
        thread.start(); // Start the thread
    }
}

Explanation:

  • The MyThread class extends the Thread class.
  • The run method contains the code that will be executed by the thread.
  • In the main method, a MyThread object is created and the start method is called to start the thread.

3. Creating a Thread by Implementing the Runnable Interface

Another way to create a thread in Java is by implementing the Runnable interface and passing an instance of the implementing class to a Thread object.

Example:

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

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable(); // Create a runnable object
        Thread thread = new Thread(myRunnable); // Pass the runnable object to a Thread object
        thread.start(); // Start the thread
    }
}

Explanation:

  • The MyRunnable class implements the Runnable interface.
  • The run method contains the code that will be executed by the thread.
  • In the main method, a MyRunnable object is created, passed to a Thread object, and the start method is called to start the thread.

4. Using Lambda Expressions to Create Threads

Since Java 8, you can use lambda expressions to create threads in a more concise way.

Example:

public class LambdaThreadExample {
    public static void main(String[] args) {
        Runnable task = () -> System.out.println("Thread is running.");
        Thread thread = new Thread(task);
        thread.start();
    }
}

Explanation:

  • A lambda expression is used to define the Runnable interface's run method.
  • The lambda expression is passed to a Thread object, and the start method is called to start the thread.

5. Common Thread Methods

start()

Starts the execution of the thread. The run method is called by the Java Virtual Machine (JVM).

run()

Contains the code to be executed by the thread. This method is called by the thread's start method.

sleep(long millis)

Pauses the execution of the current thread for the specified number of milliseconds.

join()

Waits for the thread to die. This method is used to ensure that a thread has completed its execution before the next thread starts.

isAlive()

Returns true if the thread is still running or not terminated.

6. Example Programs

Example 1: Extending the Thread Class

class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread running: " + i);
        }
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

Example 2: Implementing the Runnable Interface

class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread running: " + i);
        }
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

Example 3: Using Lambda Expressions

public class LambdaThreadExample {
    public static void main(String[] args) {
        Runnable task = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread running: " + i);
            }
        };
        Thread thread = new Thread(task);
        thread.start();
    }
}

7. Conclusion

Creating and starting a thread in Java can be done using several approaches, including extending the Thread class, implementing the Runnable interface, and using lambda expressions. Each approach has its own use cases and advantages. Understanding these methods and common thread operations can help you effectively utilize multithreading in your Java applications.

Happy coding!

Comments