Java 在不使用Callable的情况下从线程引发异常?

Java 在不使用Callable的情况下从线程引发异常?,java,multithreading,exception,concurrency,runnable,Java,Multithreading,Exception,Concurrency,Runnable,所以我在一个场景中,我有一个完全不返回任何内容的方法。(返回类型为Void)。不过我需要运行另一个线程。我知道可以使用callable抛出异常,但不幸的是,在调用Future.get()之前不会抛出异常,因为它不返回任何内容,调用Future.get()似乎是一种浪费。我的问题有没有更优雅的解决办法?下面是我遇到的问题的模型: public static void main(String[] args){ Callable<Void> upStreamer = new Cal

所以我在一个场景中,我有一个完全不返回任何内容的方法。(返回类型为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();   
}

我决定使用CompletableFuture。非常感谢塞达诺


以上代码是您现在拥有的还是您想要实现的?这是我尝试使用Callable所做的。由于我的代码的组成性质,简单地调用future.get()并不容易。另外,调用get()是一种浪费,您还希望发生什么?get()提供了一个同步点,让主线程说“好的,现在我准备好看看后台操作是如何进行的”。您要么得到一个值,要么立即得到一个ExecutionException,让您知道它失败了——这没有浪费。唯一的其他可能的概念场景将是后台线程在其正在做的任何事情中中断主线程,当然这将不那么优雅。或者,更简洁地说,@SotiriosDelimanolis刚刚说:)一旦
isDone()
返回true,您可以调用
get()
,知道它不会阻塞-如果它抛出异常,捕获它CompletableFuture呢?
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();
}