因此,我处于一种方法中,该方法绝对不返回任何内容的情况。(返回类型Void)。我需要运行另一个线程。我知道您可以使用callable引发异常,但是不幸的是,只有在调用Future.get()且因为它不返回任何内容之后才引发该异常,因此调用future.get()似乎很浪费。有没有更优雅的解决方案来解决我的问题?这是我遇到的问题的模型:
public static void main(String[] args){
Callable<Void> upStreamer = new Callable<Void>(){
public Void call() throws IOException{
throw new IOException("I want this exception to be thrown!");
}
};
FutureTask<Void> futureTask = new FutureTask<Void>(upStreamer);
Thread uploadThread = new Thread(futureTask);
uploadThread.start();
}
这是伪代码中的真正问题:
public static void main(String[] args){
new somekindOfThreadLikeThing...
//inside the method
if(criticalCondition == false){
throw new IOException("halt everything and tell the programmer what's wrong.");
}
//Import code that is the part that needs to be multithreaded but the final references will screw it up. (There are inmutable Strings involved. Code will throw uncaught exception if criticalCondition == false. This part will also throw an exception.
}.startOrWhatever();
}
我决定使用CompletableFuture。非常感谢ssedano!
http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句