signed

QiShunwang

“诚信为本、客户至上”

java使用线程异步返回结果

2021/4/26 21:11:02   来源:
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()); // 最后执行
    }
}