返回信息流Golang中可以通过下面这种代码来控制一个任务的执行时间,如果超时就不等执行结果提前return
请问Java中如何优雅地实现类似效果呢?
(可能描述的不太清楚,请直接看代码[手动捂脸])
```Go
package main
import "time"
import "fmt"
func main() {
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}
```
这段Golang代码的出处:[Go by Example: Timeouts](https://gobyexample.com/timeouts)
这是一条镜像帖。来源:北邮人论坛 / java / #62387同步于 2019/8/4
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
[问题]Java如何优雅地实现类似golang的timeout机制?
lzj0218
2019/8/4镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
ThreadPool类,可以设置线程timeout参数;谷歌出的guava线程池扩展包,解决线程执行长时间任务长时间等待返回值,使用了监听和回调函数
【 在 lzj0218 (Snail) 的大作中提到: 】
: [md]
: Golang中可以通过下面这种代码来控制一个任务的执行时间,如果超时就不等执行结果提前return
: 请问Java中如何优雅地实现类似效果呢?
: ...................
好的,我去学习一下~
【 在 yannaishi 的大作中提到: 】
: ThreadPool类,可以设置线程timeout参数;谷歌出的guava线程池扩展包,解决线程执行长时间任务长时间等待返回值,使用了监听和回调函数
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
test(1, pool, 1);
test(2, pool, 3);
pool.shutdown();
}
private static void test(int i, ExecutorService pool, int waitTimeSec) {
Future<String> f = pool.submit(() -> {
TimeUnit.SECONDS.sleep(2);
return "result " + i;
});
try {
String c = f.get(waitTimeSec, TimeUnit.SECONDS);
System.out.println(c);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("timeout " + i);
f.cancel(true);
}
}
}