How to create a completed future in java

前端 未结 6 880
不思量自难忘°
不思量自难忘° 2021-02-06 20:12

What is the best way to construct a completed future in Java? I have implemented my own CompletedFuture below, but was hoping something like this that already exist

6条回答
  •  难免孤独
    2021-02-06 20:31

    FutureTask ft = new FutureTask<>(() -> "foo");
    ft.run();
    
    System.out.println(ft.get());
    

    will print out "foo";

    You can also have a Future that throws an exception when get() is called:

    FutureTask ft = new FutureTask<>(() -> {throw new RuntimeException("exception!");});
    ft.run();
    

提交回复
热议问题