0%

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

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 {
ExecutorService service = Executors.newFixedThreadPool(2);

Future<Integer> future = service.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:11:44.191 [main] DEBUG c.MultiThreadServer - 等待结果
16:11:44.191 [pool-1-thread-1] DEBUG c.MultiThreadServer - 执行计算
16:11:45.194 [main] DEBUG c.MultiThreadServer - 结果是 50
请我喝杯咖啡吧~