What is the method for invoking Java multithreading?

There are two methods to call multiple threads in Java.

  1. Inheriting the Thread class involves creating a subclass that inherits from the Thread class, overriding the run() method to define the tasks to be executed by the thread, and then creating an object of this subclass and calling the start() method to start the thread.

Sample code:

class MyThread extends Thread {
    public void run() {
        // 线程执行的任务
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
  1. Implementing the Runnable interface involves creating a class that implements the Runnable interface, defining the run() method with the thread’s task, creating an object of that class, passing it as a parameter to the constructor of the Thread class, and finally starting the thread by calling the start() method of the Thread object.

Example code:

class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的任务
    }
}

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

Both methods can achieve multithreading functionality, but it is recommended to use the approach of implementing the Runnable interface. Java only supports single inheritance, so if a class has already inherited another class, it cannot inherit the Thread class. In this case, implementing the Runnable interface can be used to create threads. Additionally, implementing the Runnable interface can make the code clearer and more scalable.

bannerAds