50 lines
1.4 KiB
Java
Executable File
50 lines
1.4 KiB
Java
Executable File
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());
|
|
}
|
|
}
|