Saturday, May 27, 2023

How to Implement Thread in Java with Example

In Java, you can implement threads by creating a class that extends the Thread class or by implementing the Runnable interface. 

Here's an example of both approaches: 

Approach 1: Extending the Thread class


public class MyThread extends Thread {
    @Override
    public void run() {
        // Code to be executed in the thread
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        // Create an instance of the custom thread class
        MyThread thread = new MyThread();

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

Approach 2: Implementing the Runnable interface


public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // Code to be executed in the thread
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        // Create an instance of the custom runnable class
        MyRunnable myRunnable = new MyRunnable();

        // Create a Thread object and pass the runnable instance
        Thread thread = new Thread(myRunnable);

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

Both approaches achieve the same result of creating and running a new thread. The run() method contains the code that will be executed in the thread. In the example, it simply prints a message, but you can replace it with any desired functionality. 

To start a thread, you need to call the start() method on the Thread object. This will internally invoke the run() method, executing the code in a separate thread of execution. 

It's important to note that when extending the Thread class, you directly override the run() method. 

When implementing the Runnable interface, you define the code in the run() method of the Runnable implementation, and then create a Thread object passing the Runnable instance as a parameter. Both approaches have their advantages. 

Extending the Thread class allows direct access to all the features of the Thread class, while implementing the Runnable interface provides better flexibility, as it allows the class to extend other classes if needed.

Remember, in a multithreaded environment, the order of execution of threads may vary, so the output may not always be in a specific order.

No comments:

Post a Comment