What are the different methods of implementing multi-threading in Java?

There are several ways to implement multi-threading in Java.

  1. Inherit from the Thread class: Create a subclass that inherits from the Thread class and override the run() method to define the thread’s execution logic within the run() method.
public class MyThread extends Thread {
    public void run() {
        // 线程的执行逻辑
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 启动线程
    }
}
  1. Implement the Runnable interface: create a class that implements the Runnable interface and defines the logic for the thread’s execution in the run() method.
public 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 Callable and Future: create a class that implements the Callable interface and implement the call() method, defining the logic of the thread’s execution in the call() method. Submit the Callable task using the submit() method of ExecutorService, and retrieve the task’s return result through a Future object.
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallable implements Callable<Integer> {
    public Integer call() {
        // 线程的执行逻辑,返回一个结果
        return 1;
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        MyCallable callable = new MyCallable();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<Integer> future = executorService.submit(callable);
        int result = future.get(); // 获取任务的返回结果
        System.out.println(result);
        executorService.shutdown();
    }
}
  1. Utilize a thread pool: By creating a thread pool, you can submit Runnable or Callable tasks using the submit() method, and the thread pool will automatically allocate threads to execute the tasks.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池
        executorService.execute(new MyRunnable()); // 提交任务
        executorService.shutdown(); // 关闭线程池
    }
}
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds