Future和Callable
线程Thread 不支持返回值的功能 如果需要返回值可以使用Future 和 Callable。
@AllArgsConstructor
@NoArgsConstructor
public class MyCallable implements Callable<String> {
private int age;
@Override
public String call() throws Exception {
return "age " + age;
}
public static void main(String[] args) {
try {
MyCallable myCallable = new MyCallable(24);
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 3, 5L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
Future<String> future = executor.submit(myCallable);
System.out.println(System.currentTimeMillis());
String str = future.get();
System.out.println(str);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
submit() 支持 Callable 和 Runnable 两种方式。
public static void main(String[] args) {
MyCallable myCallable = new MyCallable(24);
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 3, 5L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
Future<?> future = executor.submit(new Runnable() {
@Override
public void run() {
System.out.println(1234);
}
});
System.out.println(System.currentTimeMillis());
System.out.println(future.isDone());
}
cancel(boolean mayInterruptIfRunning) 如果现车个正在运行则中断正在运行的线程,返回值表示任务取消是否成功。
get(long timeout, TimeUnit unit) 在指定的最大时间内获得返回值。如果超时测抛出异常
自定义异常策略
public class MyRejectedExecution implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//实现自定义据略逻辑
}
}
execute() 方法没有返回值, submit() 方法可以有返回值
默认情况下execute() 直接抛出异常, 可以通过自定义ThreadFactory捕获异常。
submit() 可以catch ExecutionException 捕获异常