【发布时间】:2014-08-26 17:25:43
【问题描述】:
所以我处于一种情况,我有一个绝对不返回任何内容的方法。 (返回类型无效)。我需要运行另一个线程。我知道你可以使用 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();
}
【问题讨论】:
-
上面的代码是你现在拥有的还是你想要实现的?
-
这是我尝试用 Callable 做的事情。由于我的代码组成的性质,简单地调用 future.get() 并不容易。
-
另外,关于调用 get() 是一种浪费,你还想发生什么? get() 为您的主线程提供了一个同步点,让您说“好的,现在我准备好看看后台操作是如何进行的”。你要么得到一个值,要么立即得到一个 ExecutionException 让你知道它失败了——没有浪费。唯一可能的概念场景是后台线程在它正在做的任何事情的中间中断主线程,这肯定会不那么优雅。或者,更简洁地说,@SotiriosDelimanolis 刚才所说的 :)
-
一旦
isDone()返回 true,您可以调用get()并知道它不会阻塞 - 如果它抛出异常,抓住它 -
CompletableFuture 怎么样? docs.oracle.com/javase/8/docs/api/java/util/concurrent/…
标签: java multithreading exception concurrency runnable