0Pricing
Java Academy · 课时

提交任务:Runnable 与 Callable

提交 Runnable 和 Callable 任务,并通过 Future 获取结果

提交任务:Runnable 与 Callable 是 CoddyKit 上的免费 Java Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。

Runnable 与 Callable

有两个函数式接口表示提交给 ExecutorService 的任务:

  • 可运行任务:没有返回值,不能声明受检异常
  • 可调用任务<V>:返回 V 类型的结果,可以抛出受检异常
import java.util.concurrent.*;

// Runnable — no return value
Runnable r = () -> System.out.println("Running");

// Callable<Integer> — returns a value
Callable<Integer> c = () -> {
    return 42; // or do computation
};

submit(可运行任务)

submit(Runnable) 返回一个 Future<?>。调用它的 get() 会返回 null,但可以确认任务已经完成(如果任务失败则会抛出异常)。

ExecutorService pool = Executors.newFixedThreadPool(2);

Future<?> future = pool.submit(() ->
    System.out.println("Task done on " + Thread.currentThread().getName())
);

future.get(); // waits for completion; returns null
System.out.println("Task confirmed complete");
pool.shutdown();

submit(可调用任务&lt;V&gt;)

submit(Callable) 返回一个 Future<V>。调用 future.get() 可以获取结果(在任务完成之前会阻塞)。

ExecutorService pool = Executors.newFixedThreadPool(2);

Callable<Integer> sumTask = () -> {
    int sum = 0;
    for (int i = 1; i <= 100; i++) sum += i;
    return sum;
};

Future<Integer> future = pool.submit(sumTask);
Integer result = future.get(); // blocks until done
System.out.println("Sum 1..100 = " + result); // 5050
pool.shutdown();

使用 invokeAll 提交多个可调用任务

invokeAll() 会提交一组可调用任务,并返回 Future 列表——所有任务完成后该方法才会返回:

List<Callable<String>> tasks = List.of(
    () -> "Result A",
    () -> "Result B",
    () -> "Result C"
);

ExecutorService pool = Executors.newFixedThreadPool(3);
List<Future<String>> futures = pool.invokeAll(tasks);

for (Future<String> f : futures) {
    System.out.println(f.get());
}
pool.shutdown();

invokeAny:第一个成功的结果

invokeAny() 会提交一组可调用任务,并返回第一个成功完成的任务的结果,同时取消其余任务:

List<Callable<String>> candidates = List.of(
    () -> { Thread.sleep(200); return "Slow"; },
    () -> { Thread.sleep(50);  return "Fast"; },
    () -> { Thread.sleep(100); return "Medium"; }
);

ExecutorService pool = Executors.newFixedThreadPool(3);
String winner = pool.invokeAny(candidates);
System.out.println("First: " + winner); // Fast
pool.shutdown();

execute() 与 submit()

execute(Runnable) 只负责启动任务而不等待结果——不会返回 Future;除非添加未捕获异常处理器,否则异常会丢失。submit() 会将任务包装在 Future 中,以便通过 get() 获取其中捕获的异常。

ExecutorService pool = Executors.newFixedThreadPool(2);

// execute: exception silently lost
pool.execute(() -> { throw new RuntimeException("Oops!"); });

// submit: exception captured in Future
Future<?> f = pool.submit(() -> { throw new RuntimeException("Oops!"); });
try {
    f.get();
} catch (ExecutionException e) {
    System.out.println("Caught: " + e.getCause().getMessage());
}
pool.shutdown();

带受检异常的可调用任务

与可运行任务不同,可调用任务可以抛出受检异常,因此非常适合执行输入/输出和数据库操作:

Callable<String> dbQuery = () -> {
    // This compiles fine — checked exception is declared on Callable.call()
    if (Math.random() < 0.5) throw new java.sql.SQLException("DB error");
    return "row data";
};

Future<String> f = pool.submit(dbQuery);
try {
    String data = f.get();
} catch (ExecutionException e) {
    if (e.getCause() instanceof java.sql.SQLException) {
        System.out.println("DB failed: " + e.getCause().getMessage());
    }
}

并行执行独立计算

提交多个可调用任务,可以并行执行相互独立的计算:

ExecutorService pool = Executors.newFixedThreadPool(4);

Future<Long> sumFuture  = pool.submit(() -> LongStream.rangeClosed(1,1_000_000).sum());
Future<Long> prodFuture = pool.submit(() -> LongStream.rangeClosed(1,20).reduce(1L, (a,b)->a*b));

long sum  = sumFuture.get();
long prod = prodFuture.get();
System.out.println("Sum: " + sum + ", 20!: " + prod);
pool.shutdown();

聚合可调用任务的结果

提交多个任务,并在它们全部完成后聚合结果:

int N = 8;
ExecutorService pool = Executors.newFixedThreadPool(N);
List<Future<Integer>> futures = new ArrayList<>();

for (int i = 0; i < N; i++) {
    final int chunk = i;
    futures.add(pool.submit(() -> chunk * chunk)); // i^2
}

int total = 0;
for (Future<Integer> f : futures) total += f.get();
System.out.println("Sum of squares: " + total);
pool.shutdown();

可调用任务的超时

为 future.get(timeout, unit) 传入超时时间,以避免无限期等待:

Future<String> f = pool.submit(() -> {
    Thread.sleep(5000); // slow task
    return "done";
});
try {
    String result = f.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    System.out.println("Task timed out");
    f.cancel(true); // interrupt the task
} catch (ExecutionException e) {
    System.out.println("Task failed: " + e.getCause());
}

最佳实践

最佳实践总结:

  • 优先使用 submit() 而不是 execute()——异常会被捕获
  • 需要返回值或受检异常时,请使用可调用任务
  • 务必为 future.get() 设置超时时间
  • 批处理使用 invokeAll;需要第一个响应时使用 invokeAny
  • 务必关闭线程池

快速检查

可调用任务相比可运行任务的主要优势是什么?

回顾:Runnable 与 Callable

要点:

  • 可运行任务:void,不支持受检异常;submit 返回 Future<?>,其值为 null
  • 可调用任务:返回 V,可以抛出受检异常;submit 返回 Future<V>
  • invokeAll:提交一批任务,并等待它们全部完成
  • invokeAny:返回第一个成功的结果,并取消其余任务
  • 务必使用 submit() 捕获异常

常见问题解答

「提交任务:Runnable 与 Callable」课时是免费的吗?

是的 — 「提交任务:Runnable 与 Callable」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。

「提交任务:Runnable 与 Callable」这节课中我会学到什么?

提交 Runnable 和 Callable 任务,并通过 Future 获取结果 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Java Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「提交任务:Runnable 与 Callable」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Java Academy 课中编写并运行代码吗?

能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. ExecutorService 与线程池类型
  2. 提交任务:Runnable 与 Callable
  3. Future 与错误处理
  4. 使用 ScheduledExecutorService 执行重复任务
← 返回 Java Academy