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;
    }
}
相关推荐
我也要当昏君5 分钟前
5.3 【2012统考真题】
开发语言·智能路由器·php
Kuo-Teng15 分钟前
LeetCode 73: Set Matrix Zeroes
java·算法·leetcode·职场和发展
初见无风16 分钟前
3.4 Boost库intrusive_ptr智能指针的使用
开发语言·boost
王元_SmallA18 分钟前
服务器公网IP、私网IP、弹性IP是什么?区别与应
java·后端
程序猿202319 分钟前
Python每日一练---第六天:罗马数字转整数
开发语言·python·算法
葵续浅笑37 分钟前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode
装不满的克莱因瓶1 小时前
【Java架构师】各个微服务之间有哪些调用方式?
java·开发语言·微服务·架构·dubbo·restful·springcloud
杨筱毅1 小时前
【穿越Effective C++】条款13:以对象管理资源——RAII原则的基石
开发语言·c++·effective c++
N 年 后1 小时前
cursor和传统idea的区别是什么?
java·人工智能·intellij-idea