ExecutorService executorService = Executors.newFixedThreadPool(4);
Future<String> future = executorService.submit(() -> "hello");
String s = future.get();
System.out.println(s);
executorService.shutdown(); <-- 쓰레드를 명시적으로 닫아주지 않으면 계속 열려있다 (프로세스가 종료되지 않음)
//따로 쓰레드풀을 선언하지 않아도 실행이 되며, 쓰레드를 명시적으로 닫아주지 않아도 된다
CompletableFuture<String> future = new CompletableFuture<>();
future.complete("woonsik");
System.out.println(future.get());
CompletableFuture<String> future1 = CompletableFuture.completedFuture("woonsik");
System.out.println(future1.get());
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
System.out.println("HI woonsik " + Thread.currentThread().getName());
});
future2.get();
//반환값이 있는 경우 supplyAsync()
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
return ("Hi woonsik " + Thread.currentThread().getName());
});
String s = future3.get();
System.out.println(s);
CompletableFuture<String> future4 = CompletableFuture.supplyAsync(()->{
System.out.println("hi woonsik "+ Thread.currentThread().getName());
return "hi woonsik";
}).thenApply(string -> {
System.out.println(Thread.currentThread().getName());
return string.toUpperCase();
});
//get()을 호출하기 전에 정의하는것이 불가능했지만 CompletableFuture를 사용함으로서 callBack이 가능하다
System.out.println(future4.get());
CompletableFuture<Void> future5 = CompletableFuture.supplyAsync(()->{
System.out.println("hi woonsik"+Thread.currentThread().getName());
return "hi woonsik";
}).thenAccept(string2 -> {
System.out.println(string2.toUpperCase()+ " " + Thread.currentThread().getName());
});
future5.get();
CompletableFuture<Void> future6 = CompletableFuture.supplyAsync(() -> {
System.out.println("Hi woonsik "+ Thread.currentThread().getName());
return "hi woonsik";
}).thenRun(()->{
System.out.println("more only action");
});
future6.get();
원하는 Executor(쓰레드풀)을 사용해서 실행 할 수도 있다. 두번째 인자로 Executor 전달
(기본은 ForkJoinPool.commonPool()이다)
ExecutorService executorService = Executors.newFixedThreadPool(4);
CompletableFuture<Void> future7 = CompletableFuture.runAsync(() -> {
System.out.println("hi woonsik " + Thread.currentThread().getName());
return;
}, executorService);
future7.get();
executorService.shutdown(); //<- 쓰레드를 닫아줘야 한다