public class JavaPromise {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
// submit有返回值 execute方法没有
Future<Double> cf = executorService.submit(() -> {
System.out.println(Thread.currentThread() + "===========" + System.currentTimeMillis()); // 第一个执行
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (false) {
throw new RuntimeException("test");
} else {
System.out.println("进入了else方法");
return 1.2;
}
});
System.out.println("main method" + new Date()); // 第二个执行先执行
System.out.println(cf.get()); // 等待5秒后接收返回的结果
System.out.println("main method " + new Date()); // 最后执行
}
}