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;
    }
}
相关推荐
fouryears_234172 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~2 小时前
C#---StopWatch类
开发语言·c#
桦说编程3 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
lifallen3 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研3 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
没有bug.的程序员4 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋5 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
cui__OaO5 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
阿华的代码王国5 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Zyy~5 小时前
《设计模式》装饰模式
java·设计模式