一、案例代码
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService=Executors.newCachedThreadPool();
Future<String> submit = executorService.submit(new TaskCallable());
System.out.println("1.主程序开始执行");
String result = submit.get();
System.out.println("2.主程序继续执行");
System.out.println(result);
}
}
class TaskCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("3.正在执行任务,需要等待五秒,执行任务开始");
Thread.sleep(5000);
System.out.println("4.正在执行任务,需要等待五秒,执行任务结束");
return "任务执行完成";
}
二、运行结果