From 2474bbe9132b05e352f26c8233ba87c282547f40 Mon Sep 17 00:00:00 2001 From: Antoine Date: Tue, 29 Jan 2019 17:27:47 +0100 Subject: [PATCH] first commit --- .gitignore | 3 +++ src/Main.java | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 .gitignore create mode 100755 src/Main.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8117b8f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea/ +out/ +*.iml diff --git a/src/Main.java b/src/Main.java new file mode 100755 index 0000000..6ffb5e6 --- /dev/null +++ b/src/Main.java @@ -0,0 +1,49 @@ +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; + +public class Main { + + public static void main(String[] args) throws ExecutionException, InterruptedException { + + // ***************** manual + Future f = new FutureTask<>(() -> { + System.out.println("toto"); + return 1; + }); + + showState(f); + ((FutureTask) f).run(); + + + // ***************** with pool + int nbProcs = Runtime.getRuntime().availableProcessors(); + ExecutorService exec = Executors.newFixedThreadPool(nbProcs); + Future f2 = exec.submit(() -> { + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + System.out.println("failed to sleep"); + } + }); + + showState(f2); + + System.out.println("Hello World!"); + } + + /** + * show state of future callback + * @param f + * @throws InterruptedException + * @throws ExecutionException + */ + private static void showState(Future f) + throws InterruptedException, ExecutionException { + System.out.println("is cancel : " + f.isCancelled()); + System.out.println("is done : " + f.isDone()); + System.out.println(f.get()); + } +}