반응형

ExecutorService 를 사용하여 스레드수를 제한하여 사용하기

 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor; 

 

public class ThreadTest {
    public static void main(String[] args) throws Exception {
        // 스레드풀을 사용하여 스레드 수를 제한하여 사용하기
        //final ExecutorService es = Executors.newCachedThreadPool(); // 1개이상의 스레드가 추가되었을경우 60초이상 동작을 하지 않으면 스레드를 풀에서 제거함.
        final ExecutorService es = Executors.newFixedThreadPool(2);   // 스레드수를 지정
       
        for(int i = 0 ; i < 10 ; i++){
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    ThreadPoolExecutor tpe = (ThreadPoolExecutor) es;
                    int poolSize = tpe.getPoolSize();
                    String threadName = Thread.currentThread().getName();
                    System.out.println("총 스레드 개수 : " + poolSize + " \t thread Name : " + threadName);
                }
            };
           
            es.execute(runnable);
           
            Thread.sleep(100);
        }
        es.shutdown();
    }
}
반응형

+ Recent posts