peomise
可以给予更高的自由度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package com.redisc;
import io.netty.channel.EventLoop; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import lombok.extern.slf4j.Slf4j;
import java.io.IOException; import java.util.concurrent.*;
@Slf4j(topic = "c.MultiThreadServer") public class MultiThreadServer {
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(); EventLoop eventLoop = nioEventLoopGroup.next(); DefaultPromise<Integer> defaultPromise = new DefaultPromise<>(eventLoop);
new Thread(() -> { log.debug("开始计算"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } defaultPromise.setSuccess(100); }).start();
log.debug("等待结果"); log.debug("结果是 {}",defaultPromise.get()); } }
|
输出
1 2 3
| 16:27:38.867 [main] DEBUG c.MultiThreadServer - 等待结果 16:27:38.867 [Thread-0] DEBUG c.MultiThreadServer - 开始计算 16:27:39.871 [main] DEBUG c.MultiThreadServer - 结果是 100
|
promise
除了添加结果还可以添加 setFailure()
参数可以是异常。