我有一个返回List期货的方法
List<Future<O>> futures = getFutures();
Run Code Online (Sandbox Code Playgroud)
现在我想要等到所有期货都成功处理完成,或者将来输出的任何任务抛出异常.即使一个任务抛出异常,也没有必要等待其他期货.
简单的方法是
wait() {
For(Future f : futures) {
try {
f.get();
} catch(Exception e) {
//TODO catch specific exception
// this future threw exception , means somone could not do its task
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是,例如,如果第四个未来抛出异常,那么我将不必要地等待前3个期货可用.
怎么解决这个?会以任何方式倒数闩锁帮助吗?我无法使用Future,isDone因为java doc说
boolean isDone()
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.
Run Code Online (Sandbox Code Playgroud) 在Eclipse中执行下面粘贴的代码时,我遇到以下异常大约有3次:
Exception in thread "main" java.lang.StackOverflowError
at src.Adder.recursiveSumAllNumbersUpTo(Driver.java:33)
at src.Adder.recursiveSumAllNumbersUpTo(Driver.java:37)
... *(there are 1024 lines in this stack)*
Run Code Online (Sandbox Code Playgroud)
另外2次,它按预期吐出结果(每次运行之间的时间略有不同):
Recursive: 467946
Non Recursive: 61282
Difference between recursive and non-recursive: 406664
Sum from recursive add: 19534375
Sum from non-recursive add: 19534375
Run Code Online (Sandbox Code Playgroud)
为什么异常只发生(看似)约30%的时间?
这是代码:
public class Driver {
public static void main(String[] args) {
Adder adder = new Adder();
int valueToSumTo = 6250;
long startTime = System.nanoTime();
int raSum = adder.recursiveAddAllNumbersUpTo(valueToSumTo);
long endTime = System.nanoTime();
long raDif = endTime - startTime;
System.out.println("Recursive: …Run Code Online (Sandbox Code Playgroud) 如何将inputStream转换为URL?这是我的代码:
InputStream song1 = this.getClass().getClassLoader().getResourceAsStream("/songs/BrokenAngel.mp3");
URL song1Url = song1.toUrl(); //<- pseudo code
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try {
p = Manager.createPlayer(ml);
p.start();
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud) 如果您使用JS渲染页面并需要实现安全功能,则可归结为如下所示:
var userID = getUserID();
if (userID == 1) {
html += renderDeleteButton();
}
Run Code Online (Sandbox Code Playgroud)
但用户是否能够只打开调试器并更改userID的值?