@FunctionalInterface
public interface Runnable {
public abstract void run();
}
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
<pre name="code" class="java">public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
package com.provider.future;
import java.util.Random;
import java.util.concurrent.Callable;
public class Task implements Callable<Integer>{
public Integer call() throws Exception {
Thread.sleep(10000);
Random r = new Random();
return r.nextInt(1000);
}
}
package com.provider.future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class TestFu {
public void fun1(){
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<Integer> submit = executorService.submit(new Task());
executorService.shutdown();
System.out.println(submit.isDone());
try {
Thread.sleep(1500);
System.out.println(submit.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public void fun2(){
ExecutorService executorService = Executors.newFixedThreadPool(2);
FutureTask<Integer> ft = new FutureTask<Integer>(new Task());
executorService.submit(ft);
executorService.shutdown();
System.out.println(ft.isDone());
try {
Thread.sleep(1500);
System.out.println(ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TestFu testFu =new TestFu();
testFu.fun1();
testFu.fun2();
}
}