Runnable和Callable的使用

java 复制代码
package study;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class day03_runnable和callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Task1 task1 = new Task1();
        new Thread(task1).start();

        Task2 task2 = new Task2(10);
        FutureTask<Long> futureTask = new FutureTask<Long>(task2);
        new Thread(futureTask).start();  // FutureTask实现了Runnable, 所以可以传入Thread的构造函数

        Long result = futureTask.get(); // 死等计算完成结果
        System.out.println(result);
    }
}

class Task1 implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable");
    }
}

class Task2 implements Callable<Long> {
    private long num;

    public Task2(int num) {
        this.num = num;
    }

    @Override
    public Long call() throws Exception {
        return this.num + 10;
    }
}
相关推荐
zlpzlpzyd14 小时前
nacos的openapi地址
java
沫璃染墨14 小时前
《从零入门Linux系统篇(五十四):线程篇·七——互斥锁底层原理:从原子交换到线程竞争与锁实现》
linux·运维·服务器·开发语言·c++·驱动开发·系统架构
Java后端的Ai之路14 小时前
Python进阶探索24_应用案例_linux系统的监控
linux·开发语言·python·应用·探索
程序员清风15 小时前
PydanticAI 实战:用类型安全构建可靠的 Python Agent
开发语言·python·安全
落魄实习生15 小时前
Agent Scope Java 2.x 系列【10】Middleware
java·开发语言·ai
Ramble_Naylor15 小时前
async/await:让一个线程同时等很多件事
开发语言·rust
ZealSinger15 小时前
Spring7 RestTemplate弃用迁移
java·spring·后端开发·restclient
迅猛龙办公室16 小时前
Python实现绘制同切圆
开发语言·python
朝朝辞暮i16 小时前
C++ 第 13 课:值传递 —— 为什么函数里改了,外面却没变?
java·c++·算法
弹简特16 小时前
【Java项目-企悦抽】16-抽奖模块01-获取活动完整信息接口实现
java·开发语言·状态模式·springboot