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

使用ThreadPoolExecutor结合CompletableFuture时为单个线程设置超时

Java 8异步任务调度代码示例(CompletableFuture + ThreadPoolExecutor)

我帮你把这段代码整理成规范易读的格式啦,看起来你正在用Java 8的CompletableFuture配合线程池做异步任务调度,先看整理后的原始代码:

public class ThreadTest {
    public void print(String m) {
        System.out.println(m);
    }

    public class One implements Callable<Integer> {
        public Integer call() throws Exception {
            print("One...");
            Thread.sleep(6000);
            print("One!!");
            return 100;
        }
    }

    // 你未完成的Two类我保留了原始写法
    public class Two...
}

如果要实现完整的异步调度逻辑,我给你补了一个扩展示例,把任务提交到ThreadPoolExecutor并通过CompletableFuture处理结果:

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadTest {
    public void print(String m) {
        System.out.println(m);
    }

    public class One implements Callable<Integer> {
        public Integer call() throws Exception {
            print("One...");
            Thread.sleep(6000);
            print("One!!");
            return 100;
        }
    }

    public class Two implements Callable<String> {
        public String call() throws Exception {
            print("Two...");
            Thread.sleep(3000);
            print("Two!!");
            return "Finished Two";
        }
    }

    public static void main(String[] args) {
        ThreadTest test = new ThreadTest();
        // 创建固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 用CompletableFuture异步提交任务到线程池
        CompletableFuture<Integer> futureOne = CompletableFuture.supplyAsync(() -> {
            try {
                return test.new One().call();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor);

        CompletableFuture<String> futureTwo = CompletableFuture.supplyAsync(() -> {
            try {
                return test.new Two().call();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor);

        // 异步处理任务返回结果
        futureOne.thenAccept(result -> System.out.println("One的执行结果:" + result));
        futureTwo.thenAccept(result -> System.out.println("Two的执行结果:" + result));

        // 任务完成后关闭线程池
        executor.shutdown();
    }
}

这个扩展示例里,线程池会并行处理两个任务,不用等待前一个任务完成再执行下一个,而且通过thenAccept可以在任务结束后异步处理结果,完全符合Java 8异步编程的最佳实践。

内容的提问来源于stack exchange,提问作者chrisrhyno2003

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:08:22