Java中的 FutureTask

package cn.com.zhangyimin.test;

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

/**
 * @author zhangyimin
 * @date 2022/1/5 11:28
 */
public class FutureTask1 implements Callable<String> {
    // FutureTask_1 中持有 FutureTask_2 的引用
    FutureTask<String> futureTask2;

    // 通过构造器初始化 成员变量
    public FutureTask1(FutureTask<String> futureTask2) {
        this.futureTask2 = futureTask2;
    }

    @Override
    public String call() throws Exception {
        System.out.println("T1:洗水壶");
        TimeUnit.SECONDS.sleep(1);

        System.out.println("T1:烧开水");
        TimeUnit.SECONDS.sleep(15);

        // 获取 T2 线程的茶叶
        String teas = futureTask2.get();
        System.out.println("拿到茶叶:" + teas);

        System.out.println("T1:开始泡茶...");

        return "上茶:" + teas;
    }
}



package cn.com.zhangyimin.test;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangyimin
 * @date 2022/1/5 11:29
 */
public class FutureTask2 implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("T2:洗茶壶");
        TimeUnit.SECONDS.sleep(1);

        System.out.println("T2:洗茶杯");
        TimeUnit.SECONDS.sleep(2);

        System.out.println("T2:拿茶叶");
        TimeUnit.SECONDS.sleep(1);

        return "峨眉雪尖儿";
    }
}
package cn.com.zhangyimin.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

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

/**
 * @author zhangyimin
 * @date 2022/1/5 13:03
 */
@RunWith(SpringRunner.class)
public class FutureTaskTest {

    @Test
    public void makeTea(){

        // 创建 FutureTask_2 的任务
        FutureTask<String> futureTask2 = new FutureTask<>(new FutureTask2());
        // 创建 FutureTask_1 的任务,并将 FutureTask_2 任务的引用传入
        FutureTask<String> futureTask1 = new FutureTask<>(new FutureTask1(futureTask2));

        // 创建线程 T1,来执行任务 FutureTask_1
        Thread t1 = new Thread(futureTask1);
        t1.start();

        // 创建线程 T2,来执行任务 FutureTask_2
        Thread t2 = new Thread(futureTask2);
        t2.start();

        try {
            // 获取任务 FutureTask_1 的最后一步的结果
            System.out.println(futureTask1.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>