일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- 차트쇼쇼쇼
- CDMA
- 이지형
- 위피
- 라디오
- USIM
- 그녀가말했다
- 민동현의토요명화
- 퀄컴
- 페이스북
- EV-DO Rev. B
- brew
- Java
- 김장훈
- Wibro
- 한국의 기획자들
- SWT
- itmusic
- 모던음악만만세
- VoIP
- "명탐정 코난"
- 사요
- 유희열의라디오천국
- 민동현
- 김장훈의who
- HSDPA
- 자바
- 러시아
- ETF
- 공정위
- Today
- Total
zyint's blog
Interface Executor 본문
java.util.concurrent
Interface Executor
- Sub Interface: ExecutorService, ScheduledExecutorService
- Implementing classes: AbstractExecutorService, ScheduledThreadPoolExecutor, ThreadPoolExecutor
Executor 객체는 파라미터로 넘어오는 Runnable 객체를 실행하는 인터페이스입니다.
이 Executor 인터페이스를 이용하면,
Runnable 객체를 어떤 스레드를 이용하여 실행 할지를 주요 코드와 분리하여 구조적으로 프로그램을 작성할 수 있습니다.
Executor를 사용하지 않고 Runnable을 직접 실행하는 경우
Runnable 객체를 직접 새로운 스레드를 만드는 경우 다음과 같이 사용합니다.
Executor를 사용하여 Runnable을 실행하는 경우
하지만 Executor 인터페이스를 사용하면 코드에서 직접 새로운 스레드를 생성하는 대신 다음과 같이 실행합니다.
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...
Executor의 execute() 메소드에서 현재 스레드에서 Runnable 실행할지, 새로운 스레드에서 Runnable을 실행할지를 구현할 수 있습니다.
- Caller 스레드에서 Runnable을 실행하는 경우 (DirectExecutor)
public void execute(Runnable r) {
r.run();
}
}
- 새로운 스레드를 생성하여 Runnable을 실행하는 경우 (ThreadPerTaskExecutor)
public void execute(Runnable r) {
new Thread(r).start();
}
}
Serial Executor 예제
class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
final Executor executor;
Runnable active;
SerialExecutor(Executor executor) {
this.executor = executor;
}
public synchronized void execute(final Runnable r) {
tasks.offer(new Runnable(){
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (active == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((active = tasks.poll()) != null) {
executor.execute(active);
}
}
}
Serial Executor 예제는 여러개의 Runnable을 순서대로 수행하도록 합니다.
즉, 하나의 Runnable의 수행이 끝난 후에 다음 Runnable이 수행됩니다.
SerialExecutor 객체의 execute()에서 새로운 Runnable을 정의하여 큐에 넣어서 보관합니다.
큐에 넣는 새로운 Runnable은 파라미터로 넘어온 Runnable을 실행하고,
큐에 있는 다음 Runnable을 호출하여()
에서 지정한 Executor로 큐에있는 다음 Runnable을 수행()하도록 합니다.
만일 executor가 (DirectExecutor) 처럼 동작하는 경우 현재의 스레드에서 Runnable이 하나씩 순서대로 실행될 것이고,
executor가 (ThreadPerTaskExecutor)이면, 각 Runnable마다 Thread를 생성하여 Runnable이 순서대로 하나씩 실행됩니다.
같이보기
참고자료
http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executor.html
이 글은 스프링노트에서 작성되었습니다.