start a thread in Java

Question

Answers ( 1 )

  1. Starting a thread in Java can be achieved primarily in two ways: by extending the Thread class or by implementing the Runnable interface. Below, I will describe both methods along with code examples for each.

    1. Extending the Thread class

    To create a thread by extending the Thread class, you need to:

    1. Create a new class that extends the Thread class.
    2. Override the run() method in your class. The run() method contains the code that constitutes the new thread.
    3. Create an instance of your class and call its start() method to begin executing the new thread.

    Example:

    class MyThread extends Thread {
        public void run() {
            System.out.println("My thread is running.");
            // Your code here
        }
    
        public static void main(String[] args) {
            MyThread myThread = new MyThread();
            myThread.start(); // This will call the run() method in a new thread
        }
    }
    

    2. Implementing the Runnable interface

    Another way to create a thread is by implementing the Runnable interface:

    1. Create a new class that implements the Runnable interface.
    2. Implement the run() method in your class. This method will contain the code that should run in the new thread.
    3. Create an instance of the Thread class, passing an instance of your class to the Thread constructor.
    4. Call the start() method on the Thread instance to start the new thread.

    Example:

    class MyRunnable implements Runnable {
        public void run() {
            System.out.println("My runnable is running.");
            // Your code here
        }
    
        public static void main(String[] args) {
            MyRunnable myRunnable = new MyRunnable();
            Thread thread = new Thread(myRunnable);
            thread.start(); // This will call the run() method in a new thread
        }
    }
    

    Choosing Between Thread and Runnable

    • Use Runnable if you need to extend another class since Java does not support multiple inheritance. Runnable is also a good choice if you want to implement the same run() method in multiple classes without having to inherit from a common parent.
    • Use Thread if your class is specifically designed to be a thread and will not be used for anything else that would require extending another class.

    Both methods are valid for creating and starting threads in Java. The choice between using Thread or Runnable depends on your specific use case and requirements.

Leave an answer