BhauAutomation

Java Threads

In Java, a Thread is a lightweight process that allows concurrent execution of tasks. Multithreading improves performance by executing multiple parts of a program simultaneously.

What are Java Threads?

A Thread in Java is a single unit of execution within a process. It helps execute multiple tasks concurrently. Java provides in-built support for multithreading using the Thread class and the Runnable interface.

Example: Creating a Thread by Extending Thread Class

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running...");
    }
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();  // starts the thread
    }
}
    

Output: Thread is running...

Objectives of Java Threads

Java threads help perform multiple tasks at once, utilize CPU efficiently, and improve overall application performance.

Advantages of Threads

Threads lead to better CPU utilization and faster task execution. They also make applications more responsive by running independent parts of the program simultaneously.

Limitations of Threads

However, threads increase programming complexity. They can cause issues like deadlocks, race conditions, and synchronization problems, which make debugging and maintenance harder.

Java Thread Lifecycle

A thread passes through several stages during its lifetime:

1. New: Thread is created but not started.
2. Runnable: Thread is ready and waiting for CPU time.
3. Running: Thread is currently executing.
4. Waiting/Blocked: Thread is temporarily inactive.
5. Terminated: Thread has completed its execution.

Example: Thread Lifecycle Demonstration

class LifeCycleDemo extends Thread {
    public void run() {
        System.out.println("Thread state: Running");
    }

    public static void main(String[] args) {
        LifeCycleDemo t1 = new LifeCycleDemo();
        System.out.println("Thread state: New");
        t1.start();
        System.out.println("Thread state: Runnable");
    }
}
    

Output:
Thread state: New
Thread state: Runnable
Thread state: Running

Creating Threads Using Runnable Interface

Instead of extending the Thread class, we can implement the Runnable interface for more flexibility.

Example: Using Runnable Interface

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

    public static void main(String[] args) {
        RunnableExample obj = new RunnableExample();
        Thread t1 = new Thread(obj);
        t1.start();
    }
}
    

Output: Runnable thread is running...

Best Practices

It is recommended to use Runnable interface instead of extending Thread class. Use synchronization to prevent race conditions, and prefer the Executor framework for managing multiple threads efficiently. Avoid unnecessary thread creation to save memory and CPU resources.