You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
ExecutorService를 사용하면 테스크를 스레드 풀로 보내고 Future로 저장할 수 있다는 점이 스레드와 Runnable을 이용하는 방식과 다르다.
Callable 인터페이스 : 결과를 반환하는 테스크
@FunctionalInterfacepublicinterfaceCallable<V> {
/** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */Vcall() throwsException;
}
아래 코드는 실행 서비스에 테스크를 제출해서 현재 테스크를 실행하는 스레드의 이름을 반환한다.
ExecutorServiceexecutorService = Executors.newCachedThreadPool();
// 현재 수행하고 있는 스레드의 이름을 반환Future<String> threadName = executorService.submit(newCallable<String>() {
@OverridepublicStringcall() throwsException {
returnThread.currentThread().getName();
}
});
System.out.println(threadName.get());
//람다Future<String> threadName_lamda = executorService.submit(() -> Thread.currentThread().getName());
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
동작 파라미터화 코드 전달하기
동작 파라미터 : 코드 블록 자체를 파라미터로 삼아서 메서드로 전달하는 것
-> 이를 통해 자주 바뀌는 요구사항에 효과적으로 대응할 수 있다.
filter 방법
필터링하고싶은 조건에 대해 논리값인 true, false 를 반환 하는 함수
드가 다양한 동작 (또는 전략)을 받아서 내부적으로 다양한 동작을 수행할 수 있다.
이렇게 익명클래스를 사용해서 코드 양을 줄였다.
하지만 여전히 @OverRide 코드가 길다.
6. 더 간소하게! : 람다
지금 filter 메서드는 Apple 클래스만 사용가능하다.
따라서 다음의 코드를
이것을 제네릭을 사용해서 모든 타입에 적용가능 하도록 바꿔보면
이렇게 바꾼다면 Apple클래스 뿐만이 아닌 Melon, Berry와 같은 다른 클래스에서 filter로 사용이 가능하다.
실전 예제
람다식으로 표현하면 다음처럼 간단하게 구현할 수 있다.
하지만 람다로 간단하게 스레드에서 수행할 메서드를 지정할 수 있다.
Callable 인터페이스 : 결과를 반환하는 테스크
아래 코드는 실행 서비스에 테스크를 제출해서 현재 테스크를 실행하는 스레드의 이름을 반환한다.
Beta Was this translation helpful? Give feedback.
All reactions