setDaemon(true)
)synchronized (object) {
// 하나의 스레드만 접근 가능
}
List<String> list1 = Collections.synchronizedList(new ArrayList<>());
List<String> list2 = new CopyOnWriteArrayList<>();
synchronizedList
: 쓰기엔 안전하지만 느림CopyOnWriteArrayList
: 쓰기 많으면 느림, 읽기에는 안전하고 빠름interrupt()
, volatile
, flag
사용!항목 | Vector | ArrayList |
---|---|---|
동기화 | O | X |
성능 | 느림 | 빠름 |
스레드 안전성 | O | X |
항목 | StringBuffer | StringBuilder |
---|---|---|
동기화 | O (스레드 안전) | X (싱글 스레드용) |
성능 | 느림 | 빠름 |
(매개변수) -> { 실행문 }
Runnable r = () -> System.out.println("Hello");
Function<Integer, Integer> f = x -> x + 1;
@FunctionalInterface
)@FunctionalInterface
interface MyFunc {
void method();
}
→ 람다식은 메서드 이름이 없어도 되기 때문에, 어떤 메서드인지 명확해야 함 → 1개만 허용
// 익명 클래스
Sample s = new Sample() {
public int calc(int n) {
return n + 1;
}
};
// 람다식
Sample s = n -> n + 1;
::
)::
는 특정 메서드를 참조해서 대신 호출하게 함Consumer<String> c1 = x -> System.out.println(x);
Consumer<String> c2 = System.out::println; // 메서드 참조
형태 | 의미 |
---|---|
클래스::메서드 | 정적 메서드 참조 |
참조변수::메서드 | 인스턴스 메서드 참조 |
클래스::new | 생성자 참조 |
Supplier<Date> s1 = () -> new Date();
Supplier<Date> s2 = Date::new;
인터페이스 | 역할 | 예시 |
---|---|---|
Runnable | 매개변수 없음, 반환 없음 | () -> System.out.println("run") |
Supplier<T> | 매개변수 없음, T 반환 | () -> "hello" |
Consumer<T> | T 매개변수, 반환 없음 | x -> System.out.println(x) |
Function<T,R> | T 입력 → R 출력 | x -> x + 1 |
Predicate<T> | T 입력 → boolean 출력 | x -> x > 0 |
익명 클래스 확인
→ new 인터페이스() { ... }
형태 찾기
해당 인터페이스가 추상 메서드 1개인지 확인
람다 문법으로 축약