first commit

This commit is contained in:
Antoine 2019-01-29 17:27:47 +01:00
commit 2474bbe913
2 changed files with 52 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.idea/
out/
*.iml

49
src/Main.java Executable file
View File

@ -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<Integer> f = new FutureTask<>(() -> {
System.out.println("toto");
return 1;
});
showState(f);
((FutureTask<Integer>) 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<Integer> f)
throws InterruptedException, ExecutionException {
System.out.println("is cancel : " + f.isCancelled());
System.out.println("is done : " + f.isDone());
System.out.println(f.get());
}
}