Netty源码分析(六)—Future和Promis分析

本文深入分析了Netty中的Future和Promise,它们扩展了JDK的Future模型,提供了监听器接口,避免了阻塞等待。Netty的ChannelFuture与Promise分别用于无返回值和可写入结果的异步调用,通过状态设置和监听器回调实现高效异步处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"))).get();
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值