본문으로 건너뛰기

Invoke Thread예제

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;

public class InvokeThread {
static int NUM_THREADS = 10;

public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
class MyCallable implements Callable<Integer> {
private final int threadnumber;

MyCallable(int threadnumber) {
this.threadnumber = threadnumber;
}

public Integer call() {
System.out.println("Running thread #" + threadnumber);
return threadnumber;
}
}

List<Callable<Integer>> callables = new ArrayList<Callable<Integer>>();
for (int i = 1; i <= NUM_THREADS; i++) {
callables.add(new MyCallable(i));
}
try {
List<Future<Integer>> results = exec.invokeAll(callables);
for (Future<Integer> result : results) {
System.out.println("Got result of thread #" + result.get());
}

} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (ExecutionException ex) {
ex.printStackTrace();
} finally {
exec.shutdownNow();
}

}

}
Running thread #1
Running thread #3
Running thread #2
Running thread #4
Running thread #5
Running thread #6
Running thread #7
Running thread #8
Running thread #9
Running thread #10
Got result of thread #1
Got result of thread #2
Got result of thread #3
Got result of thread #4
Got result of thread #5
Got result of thread #6
Got result of thread #7
Got result of thread #8
Got result of thread #9
Got result of thread #10