Callable的两种实现方式

目录

使用线程池
使用FutureTask包装

Callable的两种实现方式

使用线程池

package com.edgar.lesson01;

import java.util.concurrent.*;

//创建线程方式:1.实现Callable类 2.重写call()方法 3.看main方法注释
public class TestCallable implements Callable<Boolean> {
    @Override
    public Boolean call() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我在看代码" + i);
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestCallable testCallable = new TestCallable();
        //1.创建执行服务
        ExecutorService es = Executors.newFixedThreadPool(1);
        //2.执行提交
        Future<Boolean> r1 = es.submit(testCallable);
        //3.获取结果
        Boolean res = r1.get();
        System.out.println(res);
        //4,关闭服务
        es.shutdown();
        
    }
}

使用FutureTask包装

package com.edgar.lesson01;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//创建线程方式:1.实现Callable类 2.重写call()方法 3.看main方法注释
public class TestCallable2 implements Callable {
    @Override
    public Integer call() throws Exception {
        System.out.println("实现Callable接口");
        return 100;
    }

    public static void main(String[] args) {
        TestCallable2 testCallable = new TestCallable2();
        //创建多个FutureTask对象,才能多次执行线程
        FutureTask futureTask = new FutureTask(testCallable);
        FutureTask futureTask2 = new FutureTask(testCallable);
        new Thread(futureTask).start();
        new Thread(futureTask2).start();
        try {
            System.out.println(futureTask.get());
            System.out.println(futureTask2.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
posted @   EdgarStudy  阅读(606)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示