Netty源码分析(六)—Future和Promis分析
Future用来在异步执行中获取提前执行的结果
个人主页:tuzhenyu’s page
原文地址:Netty源码分析(六)—Future和Promis分析
(0) JDK中的Callable/Future模型
- Callable与Runnable的区别在于Callable线程执行有返回值,Callable/Future模型是通过Future获取Callable线程的返回值;Callable线程的执行必须通过线程池的submit()提交;
public static void main(String[] args) throws InterruptedException,ExecutionException{
final ExecutorService exec = Executors.newFixedThreadPool(5);
Callable call = new Callable(){
public String call() throws Exception{
Thread.sleep(1000 * 5);
return "Other less important but longtime things.";
}
};
Future task = exec.submit(call);
//重要的事情
Thread.sleep(1000 * 3);
System.out.println("Let's do important things.");
//其他不重要的事情
String obj = (String)task.get();
System.out.println(obj);
//关闭线程池
exec.shutdown();
}
(1) JDK AIO中的Future使用
- AsynchronousServerSocketChannel异步Socket执行accept()方法时不会阻塞线程,程序会继续执行;Future的get方法会判断任务是否执行完成,如果完成就返回结果,否则阻塞线程,直到任务完成。
public static void main(String[] args) throws Exception{
AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(30000));
while (true){
Future<AsynchronousSocketChannel> future = serverSocketChannel.accept();
AsynchronousSocketChannel socketChannel = future.get();
socketChannel.write(ByteBuffer.wrap("哈哈哈".getBytes("UTF-8"))).