Java多线程CompletableFuture代码编译错误求助
Fixing Your CompletableFuture Compilation Error
Let's walk through the issues in your code and fix them one by one:
Key Problems Causing Compilation Errors
- Duplicate public class definition: You've nested a second
public class Chaininginside the outer one. Java doesn't allow multiple top-level public classes in a single file, and this nested public class is totally unnecessary here. - Misplaced import statement: The
import java.util.concurrent.CompletableFuture;line is inside your class definition—all import statements must appear before any class declarations. - Missing import for ThreadLocalRandom: You're using
ThreadLocalRandom.current()but haven't imported this class, so the compiler can't resolve it.
Corrected Code
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; public class Chaining { public static void main(String[] args) { CompletableFuture.supplyAsync(() -> ThreadLocalRandom.current().nextInt(1, 10)) .thenApply(Math::sqrt) .thenAccept(System.out::println) .join(); } }
What Changed?
- Moved both required imports (
CompletableFutureandThreadLocalRandom) to the top of the file, right before the class definition. - Removed the duplicate nested
public class Chaining—only one top-level public class is needed for this program. - Added the missing
ThreadLocalRandomimport so the compiler recognizes the class and its methods.
This code should now compile and run smoothly: it generates a random integer between 1 and 9, calculates its square root, prints the result, and waits for the CompletableFuture to finish executing.
内容的提问来源于stack exchange,提问作者Neera Saxena
相关产品推荐
相关产品推荐

