Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
05-08 01:26
관리 메뉴

zyint's blog

Interface Executor 본문

예전글들

Interface Executor

진트­ 2009. 7. 10. 01:19

java.util.concurrent
Interface Executor

 

Executor 객체는 파라미터로 넘어오는 Runnable 객체를 실행하는 인터페이스입니다.

 

이 Executor 인터페이스를 이용하면,
Runnable 객체를 어떤 스레드를 이용하여 실행 할지를 주요 코드와 분리하여 구조적으로 프로그램을 작성할 수 있습니다.

 

Executor를 사용하지 않고 Runnable을 직접 실행하는 경우

Runnable 객체를 직접 새로운 스레드를 만드는 경우 다음과 같이 사용합니다.

new Thread(new RunnableTask1()).start();

 

 

Executor를 사용하여 Runnable을 실행하는 경우

하지만  Executor 인터페이스를 사용하면 코드에서 직접 새로운 스레드를 생성하는 대신 다음과 같이 실행합니다.

 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());
 ...

 

Executor의 execute() 메소드에서 현재 스레드에서 Runnable 실행할지, 새로운 스레드에서 Runnable을 실행할지를 구현할 수 있습니다.

 class DirectExecutor implements Executor {
     public void execute(Runnable r) {
         r.run();
     }
 }

 

 class ThreadPerTaskExecutor implements Executor {
     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이 순서대로 하나씩 실행됩니다.

 

 

 

같이보기

Executors를 이용한 멀티스레드 예제

 

 

참고자료

http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executor.html

 

 

이 글은 스프링노트에서 작성되었습니다.

Comments