蘇阿細 - FetureTask
type: channel
link: https://www.wangchouchou.com/tag/FetureTask/
items: Callable()

Callable()
type: item
date: 2021-02-12T14:17:00+00:00
description: Callable()可以有返回值，可以抛出异常Callable通过Runnable接口的实现类FetuerTask调用线程package com.sw.callable; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * @Author suaxi * @Date 2021/2/12 21:24 */ public class callableTest { public static void main(String[] args) throws ExecutionException, InterruptedException { MyThread thread = new MyThread(); FutureTask futureTask = new FutureTask(thread); //适配类 new Thread(futureTask,"A").start(); new Thread(futureTask,"B").start(); /* call()方法测试 泛型的参数 = 方法的返回值 相同的两个线程运行后只返回一个结果（有缓存） */ Object o = futureTask.get(); //获取callable返回值，此处的get可能会产生阻塞，接收返回值时可能需要等待 System.out.println(o); } } class MyThread implements Callable<String>{ @Override public String call(){ System.out.println("call()方法测试"); return "泛型的参数 = 方法的返回值"; } }