You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Chaining inside 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?

  1. Moved both required imports (CompletableFuture and ThreadLocalRandom) to the top of the file, right before the class definition.
  2. Removed the duplicate nested public class Chaining—only one top-level public class is needed for this program.
  3. Added the missing ThreadLocalRandom import 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:11:23