Skip to content

Instantly share code, notes, and snippets.

@tamtam180
Created July 11, 2012 09:08
Show Gist options
  • Save tamtam180/3089189 to your computer and use it in GitHub Desktop.
Save tamtam180/3089189 to your computer and use it in GitHub Desktop.
require "parallel"
# get from DB
urls = []
counter = 0
Parallel.each(urls) do | url |
# CPUたくさんつかう処理
# これだとForkなのでCPU分散できるけど、カウンタの共有ができない
counter += 1
end
Parallel.each(urls, :in_threads => Parallel.processor_count) do | url |
# CPUたくさんつかう処理
# Threadなので共有できるけど、GVLなのでCPU分散が・・・。
counter += 1
end
public class MySample1 {
public static void main(String[] args) throws Exception {
final AtomicInteger cnt1 = new AtomicInteger();
int[] array = new int[1000]; // ここはDBからとってくる
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
ExecutorService svc = Executors.newFixedThreadPool(4);
for (final int a : array) {
svc.execute(new Runnable() {
@Override
public void run() {
// ここでCPUをたくさんつかう処理
// Consoleに表示
System.out.println(cnt1.incrementAndGet() + "/" + a);
}
});
}
svc.shutdown();
svc.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment