JAVA 다중 스레드의Future의 실제 사용

말은 다 하지 않았는데 여기 코드를 직접 붙여 놓으세요.
package com.whb.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.whb.demo.Student;
public class FutureTest {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		List> results = new ArrayList>();
		ExecutorService es = Executors.newCachedThreadPool();
		List list = new ArrayList();
		for (int i = 0; i < 10; i++) {
			Student stu = new Student();
			stu.setAge(i);
			stu.setName("  "+i);
			list.add(stu);
		}
		for (Student student : list) {
			results.add(es.submit(new TaskStuCallable(student)));
		}
		
		for (Future res : results){
			System.out.println(res.get().toString());
			list.add(res.get());
		}
	}
	
	public static class TaskStuCallable implements Callable {
		private Student stu;
		public TaskStuCallable(Student stu) {
			super();
			this.stu = stu;
		}
		@Override
		public Student call() throws Exception {
			String tid = String.valueOf(Thread.currentThread().getId());
			System.out.printf("Thread#%s : in call
", tid); stu.setAge(Integer.valueOf(tid)); stu.setName(stu.getName()+"----"+tid); return stu; } } }

요약 사용: 여기에 사용된 스레드 풀은 Executor Services = Executors입니다.newCachedThreadPool();Future.그래도 사용을 고려해 볼 수 있어요.
ExecutorService threadPool = Executors.newCachedThreadPool();
        CompletionService cs = new ExecutorCompletionService(threadPool);
        for(int i = 1; i < 5; i++) {
            final int taskID = i;
            cs.submit(new Callable() {
                public Integer call() throws Exception {
                    return taskID;
                }
            });
        }
        for(int i = 1; i < 5; i++) {
            try {
                System.out.println(cs.take().get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
Completion 서비스는 실행하는 김에 실행할 수 있지만Future도 순서대로 출력할 수 있을 것 같습니다.직접 테스트는 다음과 같습니다.
Thread#10 : in call
Thread#19 : in call
Thread#18 : in call
Student [age=10, name=  0----10]
Thread#17 : in call
Thread#16 : in call
Thread#15 : in call
Thread#14 : in call
Thread#13 : in call
Thread#12 : in call
Thread#11 : in call
Student [age=11, name=  1----11]
Student [age=12, name=  2----12]
Student [age=13, name=  3----13]
Student [age=14, name=  4----14]
Student [age=15, name=  5----15]
Student [age=16, name=  6----16]
Student [age=17, name=  7----17]
Student [age=18, name=  8----18]
Student [age=19, name=  9----19]
됐어, 이거 내 현지 테스트 결과야.

좋은 웹페이지 즐겨찾기