Explain Threads in Java with suitable example

Threads in Java

Threads in Java allow concurrent execution of two or more parts of a program, enhancing performance, especially in applications that perform many tasks simultaneously. Each part of such a program is called a thread, and each thread defines a separate path of execution.

Creating and Running Threads in Java

In Java, there are two main ways to create a thread:

  • By extending the Thread class
  • By implementing the Runnable interface

Extending the Thread Class

When a class extends the Thread class, it needs to override the run method. This method contains the code that constitutes the new thread.

Example:

class MyThread extends Thread {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i + " - " + Thread.currentThread().getName());
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

        t1.start(); // Start the thread
        t2.start(); // Start the thread
    }
}

Implementing the Runnable Interface

When a class implements the Runnable interface, it needs to implement the run method. Then, you create a Thread object and pass the Runnable object to it.

Example:

class MyRunnable implements Runnable {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i + " - " + Thread.currentThread().getName());
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        Thread t2 = new Thread(myRunnable);

        t1.start(); // Start the thread
        t2.start(); // Start the thread
    }
}

Key Points About Thread in Java

  • start() method: Used to begin execution of the thread that is in the ready state. It moves the thread to the runnable state.
  • run() method: Contains the code that is executed by the thread.
  • Thread.sleep(milliseconds) method: Causes the current thread to suspend execution for a specified period.

Thread Lifecycle

  • New: A thread is in this state when it is created but not yet started.
  • Runnable: A thread is in this state when it is ready to run and waiting for CPU cycles.
  • Blocked: A thread is in this state when it is waiting for a monitor lock to enter or re-enter a synchronized block/method.
  • Waiting: A thread is in this state when it is waiting indefinitely for another thread to perform a particular action.
  • Timed Waiting: A thread is in this state when it is waiting for another thread to perform an action within a bounded period.
  • Terminated: A thread is in this state when it has finished its execution.

Conclusion

Understanding threads in Java is crucial for developing efficient, concurrent applications. Whether you choose to extend the Thread class or implement the Runnable interface depends on your specific use case and design requirements. By properly managing threads, you can ensure your Java applications perform well even under heavy loads.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *