What is the way to create multiple threads in Java?

There are several ways to create multiple threads in Java.

  1. Inherit the Thread class: Create a subclass that inherits from the Thread class and override the run() method. You can then create a thread by creating an instance of the subclass.
class MyThread extends Thread {
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
  1. Implementing the Runnable interface: Create a class that implements the Runnable interface and implements the run() method. Then, you can create an instance of this class and pass it as a parameter to the constructor of the Thread class to create a thread.
class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
  1. Using anonymous classes: You can directly create threads with anonymous classes, skipping the step of creating a subclass or implementing an interface.
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                // 线程执行的代码
            }
        });
        thread.start();
    }
}
  1. Using a thread pool: By employing the ExecutorService interface and ThreadPoolExecutor class from the java.util.concurrent package, you can create a thread pool and submit tasks.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        Runnable task = new Runnable() {
            public void run() {
                // 线程执行的代码
            }
        };
        executor.execute(task);
        executor.shutdown();
    }
}

The above are common ways to create multithreading in Java, the choice of which depends on specific needs and situations.

bannerAds