Created
May 27, 2021 16:57
-
-
Save FangYang970206/14fafc5b6738f42a0d9d4225b432624a to your computer and use it in GitHub Desktop.
Java测试future.get()是否抛出异常
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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