Skip to content

Instantly share code, notes, and snippets.

@FangYang970206
Created May 27, 2021 16:57
Show Gist options
  • Save FangYang970206/14fafc5b6738f42a0d9d4225b432624a to your computer and use it in GitHub Desktop.
Save FangYang970206/14fafc5b6738f42a0d9d4225b432624a to your computer and use it in GitHub Desktop.
Java测试future.get()是否抛出异常
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class FutureTest {
static class MyTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
throw new IllegalArgumentException("exception");
}
}
public static void main(String[] args) {
MyTask myTask = new MyTask();
FutureTask<Integer> task = new FutureTask<Integer>(myTask);
Thread thread = new Thread(task, "线程1");
thread.start();
try {
task.get();
} catch (Throwable throwable) {
System.out.println("can catch exception");
throwable.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment