给一个Future的简单例子:
import java.util.concurrent.*;
public class FutureUsage {
private ExecutorService executor
= Executors.newSingleThreadExecutor();
//创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
public Future<Integer> calculate(Integer input) {
return executor.submit(() -> {
System.out.println("Calculating..."+ input);
Thread.sleep(1000);
return input * input;
});
}
//这里调用submit方法,该方法接收Runnable或Callable对象作为输入参数
public void shutDown(){
executor.shutdown();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureUsage futureUsage=new FutureUsage();
Future<Integer> futureOne = futureUsage.calculate(20);
while(!futureOne.isDone()) {
System.out.println("Calculating...");
Thread.sleep(300);
}
Integer result = futureOne.get();
System.out.println("futureOne return value is " + result);
Future<Integer> futureTwo = futureUsage.calculate(4);
boolean canceled = futureTwo.cancel(true);
//调用cancel停止该任务,若成功返回true,若失败返回false。
Future<Integer> future1 = futureUsage.calculate(10);
Future<Integer> future2 = futureUsage.calculate(100);
while (!(future1.isDone() && future2.isDone())) {
System.out.println(
String.format(
"future1 is %s and future2 is %s",
future1.isDone() ? "done" : "not done",
future2.isDone() ? "done" : "not done"
)
);
Thread.sleep(300);
}
//isDone接口判断任务是否完成。
Integer result1 = future1.get();
Integer result2 = future2.get();
System.out.println(result1 + " and " + result2);
futureUsage.shutDown();
//关闭线程池。
}
}
输出结果:
Calculating...
Calculating...20
Calculating...
Calculating...
Calculating...
futureOne return value is 400
Calculating...10
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
Calculating...100
future1 is done and future2 is not done
future1 is done and future2 is not done
future1 is done and future2 is not done
100 and 10000
Future的原理是异步执行,开启多线程后,主线程可以先做其他的事情,等待一段时间后,再去查询是否执行完成,若完成则可以获取结果。
这里需要注意Future.get的方法是阻塞的,如果未完成将一直等待,可以使用带参数的get(long, TimeUnit)来确保一定时间后返回,同样给出代码:
import java.util.concurrent.*;
public class FutureUsage {
private ExecutorService executor
= Executors.newSingleThreadExecutor();
//创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
public Future<Integer> calculate(Integer input) {
return executor.submit(() -> {
System.out.println("Calculating..."+ input);
Thread.sleep(500);
return input * input;
});
}
//这里调用submit方法,该方法接收Runnable或Callable对象作为输入参数
public void shutDown(){
executor.shutdown();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureUsage futureUsage=new FutureUsage();
Future<Integer> futureOne = futureUsage.calculate(20);
while(!futureOne.isDone()) {
System.out.println("Calculating...");
Thread.sleep(300);
}
Integer result = futureOne.get();
System.out.println("futureOne return value is " + result);
Future<Integer> futureTwo = futureUsage.calculate(4);
boolean canceled = futureTwo.cancel(true);
//调用cancel停止该任务,若成功返回true,若失败返回false。
Future<Integer> future1 = futureUsage.calculate(10);
Future<Integer> future2 = futureUsage.calculate(100);
while (!(future1.isDone() && future2.isDone())) {
System.out.println(
String.format(
"future1 is %s and future2 is %s",
future1.isDone() ? "done" : "not done",
future2.isDone() ? "done" : "not done"
)
);
Integer tmpResult = null;
try {
tmpResult = future2.get(50,TimeUnit.MILLISECONDS);
} catch (Exception e) {
}
if(tmpResult != null) {
System.out.println("tmpResult: " + tmpResult);
} else {
System.out.println("tmpResult is null.");
}
Thread.sleep(30);
}
//isDone接口判断任务是否完成。
Integer result1 = future1.get();
Integer result2 = future2.get();
System.out.println(result1 + " and " + result2);
futureUsage.shutDown();
//关闭线程池。
}
}
输出结果:
Calculating...
Calculating...20
Calculating...
futureOne return value is 400
Calculating...10
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
Calculating...100
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult: 10000
100 and 10000