1.
Runnable
接口
Runnable
是 Java 中用于定义线程任务的最基本接口。它没有返回值,仅包含一个run()
方法。示例
public class RunnableExample implements Runnable {@Overridepublic void run() {System.out.println("线程任务正在执行...");}public static void main(String[] args) {Thread thread = new Thread(new RunnableExample());thread.start(); // 启动线程} }
2.
Callable<V>
接口
Callable
是Runnable
的增强版,允许线程任务有返回值并抛出异常。Callable
适用于需要计算结果的任务。
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;public class CallableExample implements Callable<Integer> {@Overridepublic Integer call() throws Exception {// 模拟计算任务return 42;}public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService executor = Executors.newSingleThreadExecutor();Future<Integer> result = executor.submit(new CallableExample());System.out.println("计算结果: " + result.get()); // 输出 42executor.shutdown();}
}
3.
Future
接口
Future
用于表示异步任务的结果,可以用于检查任务状态、取消任务以及获取结果。import java.util.concurrent.*;public class FutureExample {public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService executor = Executors.newSingleThreadExecutor();Future<Integer> future = executor.submit(() -> {Thread.sleep(1000);return 100;});if (!future.isDone()) {System.out.println("任务尚未完成...");}System.out.println("任务结果: " + future.get());executor.shutdown();} }
4.
Executor
接口和线程池
Executor
是任务执行的顶层接口,ExecutorService
提供了线程池的管理功能。线程池减少了线程创建和销毁的开销,并有效管理线程资源。import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class ExecutorExample {public static void main(String[] args) {ExecutorService executor = Executors.newFixedThreadPool(2);Runnable task1 = () -> System.out.println("任务1正在执行");Runnable task2 = () -> System.out.println("任务2正在执行");executor.execute(task1);executor.execute(task2);executor.shutdown(); // 关闭线程池} }
5.
ExecutorService
和shutdown()
方法
ExecutorService
提供了shutdown()
方法用于优雅地关闭线程池。在调用shutdown()
后,线程池不再接受新任务,但会完成已提交的任务。import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;public class ShutdownExample {public static void main(String[] args) throws InterruptedException {ExecutorService executor = Executors.newFixedThreadPool(2);executor.submit(() -> System.out.println("任务1正在执行"));executor.submit(() -> System.out.println("任务2正在执行"));executor.shutdown(); // 不接受新任务,但会完成已有任务if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {executor.shutdownNow(); // 超时后强制关闭}} }
6.
ScheduledExecutorService
ScheduledExecutorService
提供了任务调度功能,可以延迟执行任务或周期性执行任务。import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;public class ScheduledExecutorExample {public static void main(String[] args) {ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);// 延迟2秒执行scheduler.schedule(() -> System.out.println("延迟任务"), 2, TimeUnit.SECONDS);// 每隔3秒执行一次scheduler.scheduleAtFixedRate(() -> System.out.println("周期性任务"), 1, 3, TimeUnit.SECONDS);// 关闭调度器scheduler.schedule(() -> scheduler.shutdown(), 10, TimeUnit.SECONDS);} }
7.
ForkJoinPool
和ForkJoinTask
ForkJoinPool
是并行执行分治任务的执行器,适用于大规模递归计算。import java.util.concurrent.RecursiveTask; import java.util.concurrent.ForkJoinPool;public class ForkJoinExample extends RecursiveTask<Integer> {private final int start, end;public ForkJoinExample(int start, int end) {this.start = start;this.end = end;}@Overrideprotected Integer compute() {if (end - start <= 5) { // 小任务直接求和int sum = 0;for (int i = start; i <= end; i++) sum += i;return sum;} else { // 大任务分解int mid = (start + end) / 2;ForkJoinExample leftTask = new ForkJoinExample(start, mid);ForkJoinExample rightTask = new ForkJoinExample(mid + 1, end);leftTask.fork();return rightTask.compute() + leftTask.join();}}public static void main(String[] args) {ForkJoinPool pool = new ForkJoinPool();int result = pool.invoke(new ForkJoinExample(1, 10));System.out.println("计算结果: " + result);} }
8. 异步编排和
CompletableFuture
CompletableFuture
支持更灵活的异步任务组合和编排。import java.util.concurrent.CompletableFuture;public class CompletableFutureExample {public static void main(String[] args) {CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Hello").thenApply(result -> result + " World").thenAccept(System.out::println); // 打印 "Hello World"future.join(); // 等待任务完成} }
总结
Runnable
:无返回值的简单线程任务。Callable
:有返回值的任务。Future
:异步任务的结果,可以检查任务状态。ExecutorService
和shutdown()
:管理线程池,提供优雅关闭。ScheduledExecutorService
:支持任务调度。ForkJoinPool
:分治并行计算。CompletableFuture
:异步编排,用于组合和处理多个异步任务。通过这套多线程工具类和接口的结合,Java 能有效地进行并发编程,以适应复杂的多线程需求。