Created
March 14, 2016 22:25
-
-
Save koduki/ecaec4a0edec07424996 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package cn.orz.pascal.example.csv; | |
import java.util.Arrays; | |
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; | |
/** | |
* | |
* @author koduki | |
*/ | |
public class ThreadSample { | |
public static void main(String[] args) throws InterruptedException, ExecutionException { | |
long s, l; | |
for (int i = 0; i < 5; i++) { | |
s = System.nanoTime(); | |
executeTasks(Executors.newFixedThreadPool(100)); | |
l = System.nanoTime(); | |
System.out.println("newFixedThreadPool: " + (l - s) + " ns"); | |
} | |
for (int i = 0; i < 5; i++) { | |
s = System.nanoTime(); | |
executeTasks(Executors.newSingleThreadExecutor()); | |
l = System.nanoTime(); | |
System.out.println("newSingleThreadExecutor: " + (l - s) + " ns"); | |
} | |
} | |
public static void executeTasks(ExecutorService es) throws ExecutionException, InterruptedException { | |
try { | |
// タスクをリストに登録 | |
List<Callable<Integer>> tasks = Arrays.asList( | |
new ParallelTask("タスク1"), | |
new ParallelTask("タスク2"), | |
new ParallelTask("タスク3")); | |
// タスクを並列実行する | |
List<Future<Integer>> futures = null; | |
futures = es.invokeAll(tasks); | |
// 並列処理の返り値を取得する | |
Integer count = 0; | |
for (Future<Integer> future : futures) { | |
count += future.get(); | |
} | |
System.out.printf("カウントの合計は%sです。\n", count); | |
} finally { | |
if (es != null) { | |
es.shutdown(); | |
} | |
} | |
} | |
public static class ParallelTask implements Callable<Integer> { | |
private String taskName; | |
private Integer count = 0; | |
public ParallelTask(String taskName) { | |
this.taskName = taskName; | |
} | |
@Override | |
public Integer call() throws Exception { | |
// System.out.printf("%sの処理を開始します。カウントは%sです。\n", taskName, count); | |
for (int i = 0; i < 5; i++) { | |
count++; | |
// System.out.printf("%s, count=%s, i=%s\n", taskName, count, i); | |
} | |
// System.out.printf("%sの処理を終了します。カウントは%sです。\n", taskName, count); | |
return count; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment