이번 예제도 "Excutor를 사용한 thread pool 샘플" 을 토대로 작성됨
Executor 를 상속받은 ExecutorService 를 사용하여 pool 의 동작 주기를 관리한다.
void stop(..) 함수는 java api 를 참조함..

1. ConsumerThread.java 수정

package study.concurrrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

public class ConsumerThread implements Runnable {

 Thread thread;

 private static final ExecutorService pool = Executors.newFixedThreadPool(10);
 
 public void start() {
  thread = new Thread(this);
  thread.start();
 }
 
 // java api 참조
 void stop(ExecutorService pool) {
  pool.shutdown(); // Disable new tasks from being submitted
 
  try {
   // Wait a while for existing tasks to terminate
   if (! pool.awaitTermination(60, TimeUnit.SECONDS)) {
    pool.shutdownNow(); // Cancel currently executing tasks
    // Wait a while for tasks to respond to being cancelled
    if (! pool.awaitTermination(60, TimeUnit.SECONDS))
     System.err.println("Pool did not terminate");
   }
  } catch (InterruptedException ie) {
   // (Re-) Cancel if current thread also interrupted
   pool.shutdownNow();
   // Preserve interrupt status
   Thread.currentThread().interrupt();
  }
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub 
  while(!pool.isShutdown()) { 
   try {
    pool.execute(new Worker(BlockingQueueSample.getInstance().getData()));
   } catch(RejectedExecutionException e) {
    if(!pool.isShutdown()) {
     System.out.println("작업이 거부당했구만..");
    }
   }
  }
 }
}




 

 

Posted by 짱가쟁이