来自:http://ifeve.com/fork-join-5/
在Java中有两种异常:
已检查异常(Checked exceptions):这些异常必须在一个方法的throws从句中指定或在内部捕捉它们。比如:IOException或ClassNotFoundException。
未检查异常(Unchecked exceptions):这些异常不必指定或捕捉。比如:NumberFormatException。
在ForkJoinTask类的compute()方法中,你不能抛出任何已检查异常,因为在这个方法的实现中,它没有包含任何抛出(异常)声明。你必须包含必要的代码来处理异常。但是,你可以抛出(或者它可以被任何方法或使用内部方法的对象抛出)一个未检查异常。ForkJoinTask和ForkJoinPool类的行为与你可能的期望不同。程序不会结束执行,并且你将不会在控制台看到任何关于异常的信息。它只是被吞没,好像它没抛出(异常)。你可以使用ForkJoinTask类的一些方法,得知一个任务是否抛出异常及其异常种类。在这个指南中,你将学习如何获取这些信息。
task:
package com.wenbronk.forkjoin.exception;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;/**
* forkjoin 中抛出异常的处理
* Created by wenbronk on 2017/7/27.*/
public class Task extends RecursiveTask{private intarray[];private intstart, end;public Task(int[] array, int start, intend) {this.array =array;this.start =start;this.end =end;
}
@OverrideprotectedInteger compute() {
System.out.printf("task: start from %d to %d \n", start, end);if (end - start < 10) {if ((3 > start) && (3
System.out.println("paochu yichang" + start + "to" +end);throw new RuntimeException("task from" + start + "to" +end);
}try{
TimeUnit.SECONDS.sleep(1);
}catch(Exception e) {
e.printStackTrace();
}
}else{int mid = (start + end) /2;
Task task1= newTask(array, start, mid);
Task task2= newTask(array, mid, end);
invokeAll(task1, task2);
}
System.out.printf("task: end from %d to %d \n", start, end);return 0;
}
}
main:
package com.wenbronk.forkjoin.exception;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;/**
* Created by wenbronk on 2017/7/27.*/
public classExceptionMain {public static voidmain(String[] args) {int[] array = new int[100];
Task task= new Task(array, 0, 100);
ForkJoinPool forkJoinPool= newForkJoinPool();
forkJoinPool.execute(task);
forkJoinPool.shutdown();try{
forkJoinPool.awaitTermination(1, TimeUnit.DAYS);
}catch(InterruptedException e) {
e.printStackTrace();
}if(task.isCompletedAbnormally()) {
System.out.println("main::: an exception has occured \n");
System.out.printf("main:::: %s \n", task.getException());
}
System.out.printf("main: result: %d", task.join());
}
}
原文:http://www.cnblogs.com/wenbronk/p/7245765.html