/**
* 本篇主要目的为测试 Executor 的 submit() 方法及返回的 Future 对象 <br />
* 未包含 execute() 方法内容
*
* @author Victor
*
*/
public class FutureTest {
private static ExecutorService threadpool = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Runable + Future
Future<?> runFuture = threadpool.submit(new RunnableThread());
System.out.println(runFuture.get());
// (Runnable -> Callable) + Future
Future<?> runCallFuture1 = threadpool.submit(new RunnableThread(),
new String("Runnable Finished : Translate by 'submit().'"));
System.out.println(runCallFuture1.get());
// (Runnable -> Callable) + Future
Callable<String> runCall = Executors.callable(new RunnableThread(),
"Runnable Finished : Translate by 'Executors.callable(...).");
Future<String> runCallFuture2 = threadpool.submit(runCall);
System.out.println(runCallFuture2.get());
// Callable + Future
Future<String> callFuture = threadpool.submit(new CallableThread());
System.out.println(callFuture.get());
// Callable + FutureTask
FutureTask<String> futureTask = new FutureTask<>(new CallableThread());
threadpool.submit(futureTask);
System.out.println(futureTask.get());
threadpool.shutdown();
}
}
class RunnableThread implements Runnable {
@Override
public void run() {
try {
// 模拟耗时
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable 执行完成 ");
}
}
class CallableThread implements Callable<String> {
@Override
public String call() throws Exception {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Callable 执行完成 ");
return "Callable Result : " + new Date().toString();
}
}
运行结果
备忘,欢迎交流。