並行処理のための手習い - java 複数の処理を同時に行いたい 2007/07/10

シナリオ:

複数の検索エンジンを同時に検索して、その検索結果をまとめて取得したい。


javaを使用しています。
なんとなくできているようにはみえるけど。

Thread.sleepを使用して時間がかかっている感じをだしてます。
invokeAllで一斉に作業させている感じですね。
それで、それぞれ仕事がおわって結果リストになるという感じ。


package th;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test {

public static void main(String[] args) throws InterruptedException,
ExecutionException {
new App().search("検索文字列");
}

interface Searcher {
String search(String target);
}

static class App {
ExecutorService executor = new ThreadPoolExecutor(10, 10, 30000,
TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());

Searcher searcher = new Searcher() {

@Override
public String search(String target) {
/*
* do search!!
*/
return target;
}
};

/**
* <p>
* 擬似的に複数検索を行っているように振舞います。
* </p>
*
* @param searchWord
* @throws InterruptedException
* @throws ExecutionException
*/
void search(final String searchWord) throws InterruptedException,
ExecutionException {

List<Callable<String>> list = new ArrayList<Callable<String>>();
list.add(new Callable<String>() {
public String call() throws InterruptedException {
Thread.sleep(5000);
return searcher.search("yahoo:" + searchWord);
}
});

list.add(new Callable<String>() {
public String call() throws InterruptedException {
Thread.sleep(1000);
return searcher.search("google:" + searchWord);
}
});

list.add(new Callable<String>() {
public String call() throws InterruptedException {
Thread.sleep(1000);
return searcher.search("other search engine:" + searchWord);
}
});

List<Future<String>> list2 = executor.invokeAll(list);
Iterator<Future<String>> it = list2.iterator();
/*
* 結果を表示します。
*/
while (it.hasNext()) {
Future<String> future = it.next();
System.out.println(future.get());
}
executor.shutdown();
}

}

}


: