Future和Callable返回结果
@Slf4j(topic = "c.TestSubmit")
public class TestSubmit1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
//使用submit提交任务
Future<String> future = pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
log.debug("running");
Thread.sleep(1000);
return "ok";
}
});
log.debug("{}", future.get());
}
}
运行结果
16:52:46.685 c.TestSubmit [pool-1-thread-1] - running
16:52:47.686 c.TestSubmit [main] - ok
用future.get()
获取子线程
返回到主线程
的结果。
代码简化,这里使用的是JAVA8,Java8支持lambad表达式。
Callable
是用FunctionalInterface
修饰的单方法接口。
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<String> future = pool.submit(()->{
log.debug("running");
Thread.sleep(1000);
return "ok";
});
log.debug("{}", future.get());
}