| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

差分

ナビゲーションに移動 検索に移動
164 バイト追加 、 2020年2月15日 (土) 08:03
編集の要約なし
==Java 並行処理==
[[Java]]{{category 並行処理}}
==非同期に grep を実施する例1==
public static void main(String[] args) throws Exception {
if (args.length <&lt;=2) {
System.out.println("Usage: java JGrep 対象ディレクトリ 正規表現 [ファイルフィルタ]");
System.exit(-1);
String fileFilter = "";
if (args.length > &gt; 2) {
fileFilter = args[2];
}
int filesInBuketCnt = 0;
List<&lt;List<&lt;File>> &gt;&gt; buketBuket = new ArrayList<&lt;List<&lt;File>>&gt;&gt;(); List<&lt;File> &gt; fileBuket = null;
for (File file : files) {
if (filesInBuketCnt == 0) {
fileBuket = new ArrayList<&lt;File>&gt;();
}
fileBuket.add(file);
filesInBuketCnt++;
if (filesInBuketCnt > &gt; buketSize) {
buketBuket.add(fileBuket);
filesInBuketCnt = 0;
}
}
if (files !=null && filesInBuketCnt > &gt; 0) {
buketBuket.add(fileBuket);
}
int threadId = 1;
for (List<&lt;File> &gt; lstFiles : buketBuket) {
executer.execute(
new GrepCommand(threadId++,
int remain = workingThreadCount.addAndGet(-1);
System.out.println("残りのスレッド数... " + remain);
if ( remain <&lt;= 0) {
System.out.println("終了しました。");
}
=====実行例11=====
> &gt; java JGrep "C:\\work\\" ".*TEST.*" ".*\.txt$"
[006]処理中 ... WORK16.txt
public static void main(String[] args) throws Exception {
if (args.length <&lt;=2) {
System.out.println("Usage: java JGrep 対象ディレクトリ 正規表現 [ファイルフィルタ]");
System.exit(-1);
String fileFilter = "";
if (args.length > &gt; 2) {
fileFilter = args[2];
}
int filesInBuketCnt = 0;
List<&lt;List<&lt;File>> &gt;&gt; buketBuket = new ArrayList<&lt;List<&lt;File>>&gt;&gt;(); List<&lt;File> &gt; fileBuket = null;
for (File file : files) {
if (filesInBuketCnt == 0) {
fileBuket = new ArrayList<&lt;File>&gt;();
}
fileBuket.add(file);
filesInBuketCnt++;
if (filesInBuketCnt > &gt; buketSize) {
buketBuket.add(fileBuket);
filesInBuketCnt = 0;
}
}
if (files !=null && filesInBuketCnt > &gt; 0) {
buketBuket.add(fileBuket);
}
// Callable は、Runnabla と同じような役割を担うが、
// Runnable と異なり、結果を返し、例外をスローすることができる
List<&lt;Callable<&lt;Long>> &gt;&gt; tasks = new ArrayList<&lt;Callable<&lt;Long>>&gt;&gt;();
threadPool = Executors.newFixedThreadPool(THREAD_SIZE);
int threadId = 1;
for (List<&lt;File> &gt; lstFiles : buketBuket) {
tasks.add(
new GrepCommand(threadId++,
// 指定されたタスクを実行し、すべて完了すると、ステータスと結果を含む Future のリストを返す
List<&lt;Future<&lt;Long>> &gt;&gt; results = threadPool.invokeAll(tasks); for (Future<&lt;Long> &gt; f : results) {
System.out.printf("一致件数 %d 件\n", f.get().longValue());
}
* grep を実行する
*/
public static class GrepCommand implements Callable<&lt;Long> &gt; {
private int threadId;
private File[] files;

案内メニュー