쓰레드를 만들고 관리하는 작업을 애플리케이션에서 분리
쓰레드 만들기
쓰레드 관리
작업 처리 및 실행
Executor
ExecutorService
ScheduledExecutorService
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.submit(() -> {
System.out.println("Thread " + Thread.currentThread().getName());
}); // Thread pool-1-thread-1
executorService.shutdown(); // 처리중인 작업 기다렸다가 종료
executorService.shutdownNow(); // 당장 종료
}
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// 2초 딜레이후 반복 실행
scheduledExecutorService.schedule(getRunable("Hello"), 2, TimeUnit.SECONDS);
// delay(일정 시간)이 지난 후에 period(시간 간격)으로 task(작업)을 수행
scheduledExecutorService.scheduleAtFixedRate(getRunable("Repeat"), 1, 2, TimeUnit.SECONDS);
}
private static Runnable getRunable(String message) {
return () -> System.out.println(message + " " + Thread.currentThread().getName());
}
public static void main(String[] args) {
// 쓰레드 2개 생성
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(getRunable("Hello"));
executorService.submit(getRunable("Jungwan"));
executorService.submit(getRunable("The"));
executorService.submit(getRunable("Java"));
executorService.submit(getRunable("Thread"));
executorService.shutdown();
}
// Hello pool-1-thread-1
// Jungwan pool-1-thread-2
// The pool-1-thread-1
// Java pool-1-thread-2
// Thread pool-1-thread-1
private static Runnable getRunable(String message) {
return () -> System.out.println(message + " " + Thread.currentThread().getName());
}