1. 继承Thread类:创建一个类继承Thread类,并重写run()方法,然后创建该类的实例并调用start()方法来启动线程。
public class MyThread extends Thread {
    @Override
    public void run() {
        // 线程执行的代码逻辑
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
  1. 实现Runnable接口:创建一个类实现Runnable接口,并实现其run()方法,然后创建Thread的实例,将实现了Runnable接口的类的实例作为参数传递给Thread的构造函数,最后调用start()方法来启动线程。
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程执行的代码逻辑
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
  1. 使用Callable和Future:创建一个类实现Callable接口,并实现其call()方法,然后使用ExecutorService的submit()方法将实现了Callable接口的类的实例提交给线程池执行。
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<String> {
    @Override
    public String call() throws Exception {
        // 线程执行的代码逻辑
        return "Hello, World!";
    }
}

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<String> future = executorService.submit(new MyCallable());
        try {
            String result = future.get();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}
  1. 使用线程池:通过Executors类的静态方法创建一个线程池,然后将实现了Runnable接口或Callable接口的实例通过submit()方法提交给线程池执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.submit(new MyRunnable());
        executorService.shutdown();
    }
}
``
java多线程启动的四种方式

原文地址: http://www.cveoy.top/t/topic/hRlT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录