인프런 강의 "더 자바, JAVA8"(백기선님)의 강의를 듣고 정리한 글 입니다.
JAVA8에 추가된 핵심 기능들을 이해하기 쉽게 설명해 주시니 한번씩 들어보시는 것을 추천드립니다.
public class App {
public static void main(String[] args) throws Exception{
ExecutorService service = Executors.newSingleThreadExecutor();
Callable<String> hello = () -> {
Thread.sleep(2000L);
return "Hello";
};
Future<String> result = service.submit(hello);
System.out.println("Started!");
result.get(); // 블로킹
System.out.println("End!");
service.shutdown();
}
}
Future<String> result = service.submit(hello);
result.get(); // 블로킹
Future<String> result = service.submit(hello);
System.out.println(result.isDone()); // false
result.get(); // 블로킹
System.out.println(result.isDone()); // true
result.cancel(false);
public class App {
public static void main(String[] args) throws Exception{
ExecutorService service = Executors.newSingleThreadExecutor();
Callable<String> hello = () -> {
Thread.sleep(1000L);
return "Hello";
};
Callable<String> java = () -> {
Thread.sleep(2000L);
return "java";
};
Callable<String> foo = () -> {
Thread.sleep(3000L);
return "foo";
};
List<Future<String>> futures = service.invokeAll(Arrays.asList(hello, java, foo));
futures.stream().forEach(f -> {
try {
System.out.println(f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
service.shutdown();
}
}
public class App {
public static void main(String[] args) throws Exception{
ExecutorService service = Executors.newFixedThreadPool(4); // 쓰레드를 4개 생성
Callable<String> hello = () -> {
Thread.sleep(1000L);
return "Hello";
};
Callable<String> java = () -> {
Thread.sleep(2000L);
return "java";
};
Callable<String> foo = () -> {
Thread.sleep(3000L);
return "foo";
};
String result = service.invokeAny(Arrays.asList(hello, java, foo));
System.out.println(result); // 제일 짧은 hello를 출력
service.shutdown();
}
}