Java 中实现多线程的方式主要有以下几种:
继承 Thread 类
通过继承 Thread
类并重写 run()
方法来实现多线程。这种方式简单直接,但由于 Java 不支持多继承,因此如果类已经继承了其他类,则无法使用这种方式。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现 Runnable 接口
通过实现 Runnable
接口并重写 run()
方法来实现多线程。这种方式更加灵活,因为一个类可以实现多个接口。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用 Callable 和 Future
Callable
接口与 Runnable
类似,但它可以返回一个结果并且可以抛出异常。通常与 ExecutorService
和 Future
一起使用。
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Thread is running";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get());
executor.shutdown();
}
}
使用线程池
通过 ExecutorService
和 Executors
类来创建线程池,可以有效地管理线程资源,避免频繁创建和销毁线程的开销。
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("All threads are finished");
}
}
class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s) {
this.command = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
使用 CompletableFuture
CompletableFuture
是 Java 8 引入的一个类,用于异步编程,可以方便地处理异步任务的结果。
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Thread is running";
});
future.thenAccept(System.out::println);
}
}
这些方法各有优缺点,选择哪种方式取决于具体的应用场景和需求。