传统Runnable没有返回值,所以引入Callable
public interface Callable<V> {
V call() throws Exception;
}
调用采用ExecutorService调用
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
Future:结果返回类
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning); //取消任务,成功true;mayInterruptIfRunning是否取消正在运行的任务
boolean isCancelled(); //是否被取消
boolean isDone(); //是否完成
V get() throws InterruptedException, ExecutionException; //获取结果,阻塞
V get(long timeout, TimeUnit unit) //一定时间内获取结果
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask 实现Runnable和Future接口,可以直接用传统方式调用。将结果和Runnable相结合的一个结构体。
实现运用(Future)
public class CallableTest implements Callable {
@Override
public Object call() throws Exception {
Thread.sleep(3000);
return 0;
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
CallableTest callableTest = new CallableTest();
Future<Object> future = executorService.submit(callableTest);
executorService.shutdown();
try {
System.out.println("结果:");
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
实现运用(FutureTask)
public class CallableTest implements Callable {
@Override
public Object call() {
System.out.println("run");
// Thread.sleep(3000);
return 0;
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
CallableTest callableTest = new CallableTest();
Future future = executorService.submit(callableTest);
FutureTask<Object> futureTask = new FutureTask<Object>(callableTest);
new Thread(futureTask).start();
executorService.shutdown();
try {
System.out.println("结果:");
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}