What are the different ways to implement multithreading in Java?

There are several ways to implement multithreading in Java.

  1. Inherit the Thread class: Create a class that inherits from the Thread class and override the run() method to define the task the thread should perform. Then create an object of this class and call the start() method to start the thread.
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: To do this, create a class that implements the Runnable interface and override the run() method with the tasks the thread should execute. Then, create an object of this class and pass it as a parameter to the Thread class constructor. Finally, call the start() method to start the 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. Utilize the Callable and Future interfaces: Create a class that implements the Callable interface and override the call() method to define the task the thread should execute. Then, create an object of this class and pass it as a parameter to the ExecutorService’s submit() method. The Future object can be used to retrieve the results of the thread’s execution.
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class MyCallable implements Callable<String> {
    public String call() {
        // 线程要执行的任务
        return "任务执行结果";
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        MyCallable callable = new MyCallable();
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<String> future = executorService.submit(callable);
        String result = future.get();
        System.out.println(result);
        executorService.shutdown();
    }
}
  1. Use thread pool: Manage the creation and execution of threads through the thread pool provided by the Executor framework. Different types of thread pools can be created using the static methods provided by the Executors class.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new Runnable() {
                public void run() {
                    // 线程要执行的任务
                }
            });
        }
        executorService.shutdown();
    }
}
bannerAds