GGYU

threadpool 사용법 본문

프로그래밍/JAVA

threadpool 사용법

GANADARA 2018. 7. 19. 21:27
  // ExecutorService 인터페이스 구현객체 Executors 정적메서드를 통해 최대 스레드 개수가 2인 스레드 풀 생성
        ExecutorService executorService = Executors.newFixedThreadPool(2);
         
        for(int i = 0; i < 10; i++){
            Runnable runnable = new Runnable() {
                 
                @Override
                public void run() {
                    //스레드에게 시킬 작업 내용
                    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;
                     
                    int poolSize = threadPoolExecutor.getPoolSize();//스레드 풀 사이즈 얻기
                    String threadName = Thread.currentThread().getName();//스레드 풀에 있는 해당 스레드 이름 얻기
                     
                    System.out.println("[총 스레드 개수:" + poolSize + "] 작업 스레드 이름: "+threadName);
                     
                    //일부로 예외 발생 시킴
                    int value = Integer.parseInt("예외");
                }
            };
     
            //스레드풀에게 작업 처리 요청
            executorService.execute(runnable);
            //executorService.submit(runnable);
             
             
            //콘솔 출력 시간을 주기 위해 메인스레드 0.01초 sleep을 걸어둠.
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             
             
        }
         
        //스레드풀 종료
        executorService.shutdown();




import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class CallbackExam {
    private ExecutorService executorService;
    
    public CallbackExam() {
        executorService = Executors.newFixedThreadPool(
                Runtime.getRuntime().availableProcessors()
        );
    }
    
    private CompletionHandler<Integer, Void> callback = 
            new CompletionHandler<Integer, Void>() {
 
                @Override
                public void completed(Integer result, Void attachment) {
                    System.out.println("completed() 실행: " + result);
                }
 
                @Override
                public void failed(Throwable exc, Void attachment) {
                    System.out.println("failed() 실행: " + exc.toString());
                }
                
    };
    
    public void doWork(final String x, final String y) {
        Runnable task = new Runnable() {
            public void run() {
                try {
                     int intX = Integer.parseInt(x);
                     int intY = Integer.parseInt(y);
                     
                     int result = intX + intY;
                     callback.completed(result, null);
                     
                } catch (NumberFormatException e) {
                    callback.failed(e, null);
                }
            }
        };
        executorService.submit(task);
    }
    
    public void finish() {
        executorService.shutdown();
    }
    
    public static void main(String[] args) {
        CallbackExam exam = new CallbackExam();
        exam.doWork("4""7");
        exam.doWork("4""자바");
        exam.finish();
    }
}



출처: http://palpit.tistory.com/732 [palpit's log-b]

'프로그래밍 > JAVA' 카테고리의 다른 글

크리티컬섹션 처리  (0) 2018.07.19
thread 사용법  (0) 2018.07.19
디렉토리 조회  (0) 2018.07.19
Input/OutputStream  (0) 2018.07.19
BufferedReader/Writer 사용법  (0) 2018.07.19
Comments