在本节中,将学习能获得关于 ForkJoinPool 类状态的哪些信息及如何获得。
本节的示例代码在 com.elanzone.books.noteeg.chpt8.sect05 package中
Task 类 : 扩展 RecursiveAction
private int array[]; private int start, end; public Task(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; }
@Override protected void compute() { if (end - start > 100) { int mid = (start + end) / 2; Task task1 = new Task(array, start, mid); Task task2 = new Task(array, mid, end); task1.fork(); task2.fork(); task1.join(); task2.join(); } else { for (int i = start; i < end; i++) { array[i]++; try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } } }
控制类 : Main
public static void main(String[] args) throws Exception { ForkJoinPool pool = new ForkJoinPool(); int array[] = new int[10000]; Task task1 = new Task(array, 0, array.length); pool.execute(task1); while (!task1.isDone()) { showLog(pool); TimeUnit.SECONDS.sleep(1); } pool.shutdown(); pool.awaitTermination(1, TimeUnit.DAYS); showLog(pool); System.out.printf("Main: End of the program.\n"); }
private static void showLog(ForkJoinPool pool) { System.out.printf("**********************\n"); System.out.printf("Main: Fork/Join Pool log\n"); System.out.printf("Main: Fork/Join Pool: Parallelism: %d\n", pool.getParallelism()); System.out.printf("Main: Fork/Join Pool: Pool Size: %d\n", pool.getPoolSize()); System.out.printf("Main: Fork/Join Pool: Active Thread Count: %d\n", pool.getActiveThreadCount()); System.out.printf("Main: Fork/Join Pool: Running Thread Count: %d\n", pool.getRunningThreadCount()); System.out.printf("Main: Fork/Join Pool: Queued Submission: %d\n", pool.getQueuedSubmissionCount()); System.out.printf("Main: Fork/Join Pool: Queued Tasks: %d\n", pool.getQueuedTaskCount()); System.out.printf("Main: Fork/Join Pool: Queued Submissions: %s\n", pool.hasQueuedSubmissions()); System.out.printf("Main: Fork/Join Pool: Steal Count: %d\n", pool.getStealCount()); System.out.printf("Main: Fork/Join Pool: Terminated : %s\n", pool.isTerminated()); System.out.printf("**********************\n"); }
在本节中,实现了一个任务用 ForkJoinPool 类和扩展了 RecursiveAction(能在 ForkJoinPool 类中执行的一中任务) 的 Task 类来增加一个数组的元素值。 当各任务在处理数组时,输出 ForkJoinPool 类的状态信息到终端。使用了以下方法来获得 ForkJoinPool 类的状态: