java多线程的实现的各种方法?
在 Java 中,实现多线程主要有以下几种方法:
- 继承 Thread 类:通过创建一个继承自 Thread 类的子类,并重写 run () 方法来定义线程的执行逻辑。然后创建该子类的实例,并调用 start () 方法启动线程。例如,以下代码创建了一个简单的线程类:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程正在运行");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}

- 实现 Runnable 接口:创建一个实现 Runnable 接口的类,并重写 run () 方法。然后创建该类的实例,并将其作为参数传递给 Thread 类的构造函数,最后调用 start () 方法启动线程。例如:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程正在运行");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}

- 使用 Callable 和 Future 接口:Callable 接口类似于 Runnable 接口,但它可以返回一个结果。Future 接口用于获取 Callable 任务的结果。可以通过创建一个实现 Callable 接口的类,并重写 call () 方法来定义线程的执行逻辑和返回结果。然后使用 ExecutorService 提交 Callable 任务,并通过 Future 获取任务的结果。例如:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 1 + 1;
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
Integer result = future.get();
System.out.println("结果:" + result);
executor.shutdown();
}
}

- 使用线程池:线程池可以管理和复用线程,减少线程创建和销毁的开销。可以通过使用 ExecutorService 接口和其实现类来创建线程池,并提交任务到线程池中执行。例如:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println(“线程正在运行”);
});
}
executor.shutdown();
}
}