Created
April 10, 2018 05:35
-
-
Save vichu/dc32f724737f92b39b816c6448870437 to your computer and use it in GitHub Desktop.
An example to illustrate how to use Future
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package completablefutureexample; | |
import java.util.Random; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
public class App { | |
public static void main(String[] args) throws ExecutionException, InterruptedException { | |
//Future example | |
ExecutorService executorService = Executors.newFixedThreadPool(2); | |
Future<Integer> future = executorService.submit(() -> { | |
System.out.println("Executing a task."); | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
return new Random().nextInt(20); | |
}); | |
while (!future.isDone()) { | |
System.out.println("Task not yet done..."); | |
Thread.sleep(100); | |
} | |
System.out.println("The future is resolved. Value generated = " + future.get()); | |
executorService.shutdown(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment