所以我的情况是,我有一个方法,什么都不返回。 (返回类型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();
}
答案 0 :(得分:1)
我决定使用CompletableFuture。非常感谢ssedano!
http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html