Callable线程返回结果

标签:

本文出自jvm123.com-java技术分享站:http://jvm123.com/2020/04/callable-xian-cheng.html

可使用callable实例化一个FutureTask,FutureTask被用于实例化线程,线程执行后, FutureTask 的对象将会得到线程执行后的返回值。

package com.yawn.juc;

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

/**
 * Callable<V> 返回结果的线程
 * @author yawn http://jvm123.com
 * 2020/4/26 17:19
 */
public class FutureTaskTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread myThread = new MyThread();
        FutureTask<String> futureTask = new FutureTask<>(myThread);
        new Thread(futureTask).start();
        String str = futureTask.get();
        System.out.println(str);

        // 计算
        FutureTask<Integer> fTask = new FutureTask<>(new IntThread());
        new Thread(fTask).start();
        Integer sum = fTask.get();
        System.out.println(sum);
    }

}

class MyThread implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(2000);
        return "MyThread is done!";
    }
}

class IntThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        return sum;
    }
}

发表评论