0%

java | netty future

参考

同步

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
package com.redisc;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
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();

Future<Integer> future = eventLoop.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
log.debug("执行计算");
Thread.sleep(1000);
return 50;
}
});
// 阻塞拿返回
log.debug("等待结果");
log.debug("结果是 {}", future.get());
}
}

输出

1
2
3
16:16:20.794 [main] DEBUG c.MultiThreadServer - 等待结果
16:16:20.795 [nioEventLoopGroup-2-1] DEBUG c.MultiThreadServer - 执行计算
16:16:21.799 [main] DEBUG c.MultiThreadServer - 结果是 50

异步

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
package com.redisc;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
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();

Future<Integer> future = eventLoop.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
log.debug("执行计算");
Thread.sleep(1000);
return 50;
}
});
future.addListener(new GenericFutureListener<Future<? super Integer>>() {
@Override
public void operationComplete(Future<? super Integer> future) throws Exception {
// 虽然 getNow 是非阻塞的,但是,只要回调执行,就说明结果已经返回了
log.debug("结果是 {}", future.getNow());

}
});
}
}

输出

1
2
16:18:26.934 [nioEventLoopGroup-2-1] DEBUG c.MultiThreadServer - 执行计算
16:18:27.939 [nioEventLoopGroup-2-1] DEBUG c.MultiThreadServer - 结果是 50
请我喝杯咖啡吧~